Rust – il linguaggio – 7

pogo5

Oggi qui: /usr/local/share/doc/rust/html/book/loops.html, continuando da qui.

Cicli

Rust currently provides three approaches to performing some kind of iterative activity. They are: loop, while and for.

loop

loop {
    println!("Loop forever!");
}

while

fn main() {
    let mut x = 5; // mut x: i32
    let mut done = false; // mut done: bool

    while !done {
        x += x - 3;

        println!("{}", x);

        if x % 5 == 0 {
            done = true;
        }
    }
}

rs7-0

while loops are the correct choice when you’re not sure how many times you need to loop.

If you need an infinite loop, you may be tempted to write this:

while true {

However, loop is far better suited to handle this case:

loop {

Rust’s control-flow analysis treats this construct differently than a while true, since we know that it will always loop. In general, the more information we can give to the compiler, the better it can do with safety and code generation, so you should always prefer loop when you plan to loop infinitely. Ottimizzazione e chiarezza del codice :grin:

for

The for loop is used to loop a particular number of times. Rust’s for loops work a bit differently than in other systems languages, however. Rust’s for loop doesn’t look like this “C-style” for loop. Non metto il codice C, se poi leggo di fretta capace che mi perdo :roll:

[I]t looks like this:

for x in 0..10 {
    println!("{}", x); // x: i32
}

In slightly more abstract terms,

for var in expression {
    code
}

The expression is an iterator (prossimamente, qui: /usr/local/share/doc/rust/html/book/iterators.html). The iterator gives back a series of elements. Each element is one iteration of the loop. That value is then bound to the name var, which is valid for the loop body. Once the body is over, the next value is fetched from the iterator, and we loop another time. When there are no more values, the for loop is over.

In our example, 0..10 is an expression that takes a start and an end position, and gives an iterator over those values. The upper bound is exclusive, though, so our loop will print 0 through 9, not 10.

Rust does not have the “C-style” for loop on purpose. Manually controlling each element of the loop is complicated and error prone, even for experienced C developers.

fn main() {
    for x in 0..10 {
        print!("{} ", x); // x: i32
    }
    println!("");
}

rs7-1

Enumerate

When you need to keep track of how many times you already looped, you can use the .enumerate() function.

Per gli intervalli (ranges):

fn main() {
    for (i,j) in (5..10).enumerate() {
        println!("i = {} and j = {}", i, j);
    }
}

rs7-2

Con gli iteratori:

fn main() {
    let lines = "hello\nworld".lines();

    for (linenumber, line) in lines.enumerate() {
        println!("{}: {}", linenumber, line);
    }
}

rs7-3

Uscita anticipata dall’iterazione

Let’s take a look at that while loop we had earlier:

let mut x = 5;
let mut done = false;

while !done {
    x += x - 3;

    println!("{}", x);

    if x % 5 == 0 {
        done = true;
    }
}

We had to keep a dedicated mut boolean variable binding, done, to know when we should exit out of the loop. Rust has two keywords to help us with modifying iteration: break and continue.

In this case, we can write the loop in a better way with break:

fn main() {
    let mut x = 5;

    loop {
        x += x - 3;

        println!("{}", x);

        if x % 5 == 0 { break; }
    }
}

rs7-4We now loop forever with loop and use break to break out early. Issuing an explicit return statement will also serve to terminate the loop early.

fn main() {
    let mut x = 5;

    loop {
        x += x - 3;

        println!("{}", x);

        if x % 5 == 0 { return; }
    }
}

continue is similar, but instead of ending the loop, goes to the next iteration. This will only print the odd numbers:

fn main() {
    for x in 0..10 {
        if x % 2 == 0 { continue; }

        print!("{} ", x);
    }
    println!("");
}

rs7-5

Labels con i loops

You may also encounter situations where you have nested loops and need to specify which one your break or continue statement is for. Like most other languages, by default a break or continue will apply to innermost loop. In a situation where you would like to a break or continue for one of the outer loops, you can use labels to specify which loop the break or continue statement applies to. This will only print when both x and y are odd:

fn main() {
    'outer: for x in 0..6 {
        'inner: for y in 0..6 {
            if x % 2 == 0 { continue 'outer; } // continues the loop over x
            if y % 2 == 0 { continue 'inner; } // continues the loop over y
            println!("x: {}, y: {}", x, y);
        }
    }
}

rs7-6

Notare che la label dev’essere quotata à la Lisp.

:mrgreen:

LOL – Let Over Lambda

Quando uno ridefinisce così un acronimo universalmente riconosciuto al volo dev’essere un nerd davvero über. Ma ‘spetta’n’attimino: è un lisper, quelli che usano il programmable programming language, quello delle macro, quelle vere, mica la robetta di C/C++.
OK, adesso mi spiego :roll:
logoSto parlando di Doug Hoyte, ecco come si presenta, qui.
Sì ha un blog da seguire, cioè no, non è aggiornato, abbandonato. Anche la foto di allora è di quando era un über-nerd giovane. Adesso scrive su Hoytech che Feedly si rifiuta di RSSare. Da seguire autonomamente.

Anche perché la novità è non nuovissima ma di quelle ***BREAKING NEWS***: Let Over Lambda—50 Years of Lisp.

Un libro di quelli intimidatori per la mole, 384 pagine 15×23 cm, pieno di Common Lisp.
Poco per volta, per chi ha pazienza e pochi €, Doug lo sta mettendolo online; anche se è uno di quelli che qualificano la propria biblioteca :wink: ma attenti che se lo vedo lo prendo, vedo se ci sono segnalibri, lo apro e controllo sottolineature e note, nèh.

Io l’ho subito messo tra le cose da fare, non subitissimo ma abbastanza urgenti (non urgentissime). Altamente consigliato ai lispers tutti. E un ringraziamento particolare al prof Lipari :grin: che me l’ha segnalato.

:mrgreen:

Visto nel Web – 220

Dalla prossima volta si cambia; cioè sempre uguale ma sempre meglio, ci saranno le categorie. Lo script è pronto (forse), ma è solo la rima versione, consigli e suggerimenti benvenuti.
Intanto ecco cosa ho visto nel Web.
programmer apiumtech
Questo è il problema del nostro paese
::: AlfonsoFuggetta

Termini. Informiamo i sigg. viaggiatori
::: MarcoAlici

Software Hall of Fame Member Ed Yourdon Dies
::: Slashdot

Meet Snoopy: The DIY drone that tracks your devices just about anywhere
::: Ars Technica

When Virtual Reality Meets Education
::: TechCrunch

CTxUD2nXAAA-qXR

Linux Foundation Update
::: The Linux Foundation

Finally Calculated: All the Legal Positions In a 19×19 Game of Go
::: Slashdot

R.I.P. John McCreesh
::: The Document Foundation

Introducing Go
::: Caleb Doxsey

To Solve a Rubik’s Cube In 1 Second, It Takes a Robot
::: Slashdot

CVvrUtIWsAASidr.png-large

I buoni consigli e il cattivo esempio
::: Tech Economy

weather information
::: The Ubuntu Incident

10 anni di scuola libera a Bolzano con FUSS
::: LibreItalia

Marvin Minsky, Pioneer in Artificial Intelligence, Dies at 88
::: The New York Times ::: GeekWire

Robot che fanno gli infermieri, i badanti, gli inservienti
::: iWaxen

11140014_10205330182400166_7187371600400959415_n

There’s a better model for innovation than Silicon Valley
::: HarvardBiz

Perplessità condivisibili su novella al CAD
::: carlopiana

Facebook Building World’s ‘Most Advanced’ Data Center In Irish Village
::: Slashdot

Marvin Minsky on ‘the beauty of the #Lisp language”: http://www.webofstories.com/play/marvin.minsky/44
::: RainerJoswig

ph level

Marvin Minsky declara: “tipado dinamista hasta la sepultura”
::: spectrumgomas

Persistent history in Bash – redux
::: Eli Bendersky

Adventure: AWK
::: LinuxCommand

Why Spacemacs?
::: lunaryorn

Riecco il trojan di Stato: sulla cybersicurezza una partita di potere
Beppu Pisane era un dilettante
::: L’Espresso

12341255_1059308150757353_3591937044500359063_n

Absolutely crucial
::: fabiochiusi ::: csoghoian

We Asked a Robot to Write an Obit for AI Pioneer Marvin #Minsky | WIRED
::: RadioProzac

USA 2016, il fact checking di Google svelerà in diretta l’incoerenza dei candidati
::: Downloadblog

Sorprese inaspettate e pillole di robotica
::: Grab the Blaster

堅実に進化した良いマクロシステムをみたかったら Racket やろうよ
::: kmizu

hl

Overfitting
::: jakevdp

Some wonderful bits of Minskiana
::: danieldennett

Google’s AI just beat a pro at the game of Go
::: MIT_CSAIL

Crazy to see Facebook’s ad revenue growth continue to accelerate
::: jandawson

Ora per #ubuntuphone sono supportati come linguaggi di sviluppo #Python e #GoogleGo
::: n1k9

googling

Always funny seeing: “#Haskell a plus” for unrelated jobs
::: dogodel

I would probably rejoin Haskell
::: aphyr

Essentially, Facebook is eating the Internet
::: fabiochiusi

Avoid Javaisms
::: volothamp

12592541_1157334637618328_6814793304251405582_n

Remembering Minsky
::: Edge

Apple, 600 nuovi posti di lavoro a Napoli? No, saranno 600 studenti
::: Corriere Innovazione

Purescript Reference: Pattern Matching
::: Purescript

Computer Beats Go Champion
frazie Sylvie per le segnalazioni :grin:
::: Slashdot ::: Nature ::: Nature

L’urgence d’en sortir !
::: La Quadrature du Net

CZb9rIRUcAA4_nW.jpg-large

Giornata europea privacy: “Libertà, non algoritmo”. E il pm Spataro attacca Carrai
::: la Repubblica

Who Controls Your Facebook Feed
::: Slate Magazine

Così Morozov ci costringe a mettere in discussione il nostro rapporto con la tecnologia
::: Codice Edizioni

Major breaking news
::: dcavedon

There are two kinds of true magic
::: mr_whythat

12642473_1014956291884488_2962194838548939156_n

I made some particle effects for the Code in the Dark editor
::: JoelBesada

The Widely Reported ISIS Encrypted Messaging App Is Not Real
::: Slashdot

Attackers Use Microsoft Office To Push BlackEnergy Malware
::: Slashdot

Studente acquista per errore il dominio Google.com per 12 dollari: la curiosa ricompensa di Google
::: Downloadblog

State of Clojure 2015 Survey Results
::: Cognitect

PatFumetto

Slashdot and SourceForge Sold, Now Under New Management
::: Slashdot

«Schiavi del digitale»
::: Luca De Biase

Guide to interpreting developer job ads
::: I am Programmer

Windows Phone Is An Ex-Platform
::: TechCrunch

Microsoft, il sonno della ragione
::: Tech Economy

Foto LaPresse 25-06-2013 Roma Cronaca Comizio di Giuliano Ferrara a sostegno di Silvio Berlusconi

Non possiamo accontentarci: un VERO #Foia ora!
::: foia4italy

Program Haskell with Lisp Syntax Using Liskell or Lisk
devo ancora capire se ha senso; e se sì quale :roll:
::: readwrite

No al Foia giocattolo: l’Italia ha bisogno di una vera libertà di accesso ai dati. Il governo agisca
::: Riparte il futuro

Pavel Durov, il fondatore di Telegram, è cresciuto a Torino
::: Quotidiano Piemontese

Apple reportedly has hundreds of people working on a secret virtual reality team
::: The Verge

technology-quotes-funny

Congress to investigate US involvement in Juniper’s backdoor
::: Engadget

Facebook Expands Online Commerce Role, But Says “No Guns, Please”
::: Slashdot

Go, Marvin Minsky, and the Chasm that AI Hasn’t Yet Crossed
An expert in AI separates fact from hype in the wake of DeepMind’s victory over humans in the most challenging game of all
::: Medium

Recognizing correct code
::: MIT News

Free element14 Raspberry Pi User Guide
::: element14

CZ_VdGmW0AIj8tD

the Italian defense organization – Army, Navy and Air Force Migration
::: eniogemmo

Coordinated concurrent programming in Syndicate
::: Lambda the Ultimate

Il telegrafista sacrificale
::: manteblog

Gli autobus che si guidano da soli nei Paesi Bassi
::: Il Post

i love you2

Rust – il linguaggio – 6

hitchhiker_guide

Continuo da qui, oggi qui: /usr/local/share/doc/rust/html/book/comments.html.

Commenti

Così:
// Line comments are anything after ‘//’ and extend to the end of the line.
let x = 5; // this is also a line comment.

E quando sono tante linee conviene usare i doc comments, use /// instead of //, and support Markdown notation inside. Non riporto l’esempio; poi [t]here is another style of doc comment, //!, to comment containing items (e.g. crates, modules or functions), instead of the items following it. Commonly used inside crates root (lib.rs) or modules root (mod.rs). Niente esempio nemmeno qui.
You can use the rustdoc tool to generate HTML documentation from these doc comments, and also to run the code examples as tests!

if

Rust’s take on if is not particularly complex, but it’s much more like the if you’ll find in a dynamically typed language than in a more traditional systems language. So let’s talk about it, to make sure you grasp the nuances.

if is a specific form of a more general concept, the ‘branch’. The name comes from a branch in a tree: a decision point, where depending on a choice, multiple paths can be taken.

In the case of if, there is one choice that leads down two paths:

fn main() {
    let x = 5;

    if x == 5 {
        println!("x is five!");
    }
}

rs6-0

If we changed the value of x to something else, this line would not print. More specifically, if the expression after the if evaluates to true, then the block is executed. If it’s false, then it is not.

If you want something to happen in the false case, use an else:

fn main() {
    let x = 6;

    if x == 5 {
        println!("x is five!");
    } else {
        println!("x is not five ☹ ");
    }
}

rs6-1

If there is more than one case, use an else if:

fn main() {
    let x = 7;

    if x == 5 {
        println!("x is five!");
    } else if x == 6 {
        println!("x is six!");
    } else {
        println!("x is not five or six :(");
    }
}

No, niente screenshot :roll:
Però :grin: ecco la novità…
This is all pretty standard. However, you can also do this:

fn main() {
    let x = 5;

    let y = if x == 5 {
        10
    } else {
        15
    }; // y: i32
}

Which we can (and probably should) write like this:

fn main() {
    let x = 5;

    let y = if x == 5 { 10 } else { 15 }; // y: i32
}

:grin: This works because if is an expression. The value of the expression is the value of the last expression in whichever branch was chosen. An if without an else always results in () as the value.
Proprio come nella famiglia di linguaggi che mi piacciono :wink:

:mrgreen:

Approssimazioni su numeri enormemente grandi – 2

hk1

Continuo da qui.

JavaScript (nodejs) si comporta davvero male. Va in overflow senza accorgersene o avvisare. Provo con numeri sempre enormi ma più piccoli:

a6

OK con 999’999’999’999’999, cioè 10^15 – 1.
E ovviamente:

a7

Ma quest’ultima verifica viene superata per i numeri grandi, quelli originali, da Python, Racket e newLISP? Verifico, ecco:

a8

Nel mondo Unix/Linux la precisione arbitraria esiste da sempre; un tool che uso abitualmente come calcolatrice, calc funziona con numeri grandi a piacere:

a9

Ma calc non fa parte delle distro, bisogna installarlo, potreste dire. Vero ma per questo possiamo fare senza, c’è bc:

a10

E prima ancora di bc (ma sono troppo giovane per ricordarlo) c’era dc. E pare che non se lo ricordi nessuno; ho provato a googlare un po’ ma mi sono stufato prima di ottenere qualcosa di meglio di questo

a11

Il C++ si comporta non diversamente dal Fortran, vedi per esempio qui:
Fundamental types.
Chissà Java e gli altri? Lasciato come esercizio :roll:

:mrgreen:

Rust – il linguaggio – 5

 Il progetto originale, non realizzato

Il progetto originale, non realizzato

Oggi qui: /usr/local/share/doc/rust/html/book/primitive-types.html continuando da qui.

Tipi primitivi

The Rust language has a number of types that are considered ‘primitive’. This means that they’re built-in to the language. Rust is structured in such a way that the standard library also provides a number of useful types built on top of these ones, as well, but these are the most primitive.

Booleani

Rust has a built in boolean type, named bool. It has two values, true and false.

char

The char type represents a single Unicode scalar value. You can create chars with a single tick: (')

let x = 'x';
let two_hearts = '💕';

Unlike some other languages, this means that Rust’s char is not a single byte, but four.

Tipi numerici

Rust has a variety of numeric types in a few categories: signed and unsigned, fixed and variable, floating-point and integer.

These types consist of two parts: the category, and the size. For example, u16 is an unsigned type with sixteen bits of size. More bits lets you have bigger numbers.

If a number literal has nothing to cause its type to be inferred, it defaults:

let x = 42; // x has type i32
let y = 1.0; // y has type f64

Here’s a list of the different numeric types, with links to their documentation in the standard library: i8, i16, i32, i64, u8, u16, u32, u64, isize, usize, f32, f64.

Con segno e senza segno

(Signed and Unsigned). Integer types come in two varieties: signed and unsigned. Unsigned types use a u for their category, and signed types use i. The i is for ‘integer’. So u8 is an eight-bit unsigned number, and i8 is an eight-bit signed number.

Tipi fixed size

Fixed size types have a specific number of bits in their representation. Valid bit sizes are 8, 16, 32, and 64. So, u32 is an unsigned, 32-bit integer, and i64 is a signed, 64-bit integer.

Tipi variable size

Rust also provides types whose size depends on the size of a pointer of the underlying machine. These types have ‘size’ as the category, and come in signed and unsigned varieties. This makes for two types: isize and usize.
Nota per me: mystery mysteryous here :roll:

Tipi floating point

Rust also has two floating point types: f32 and f64. These correspond to IEEE-754 single and double precision numbers.

Arrays

The most basic is the array, a fixed-size list of elements of the same type. By default, arrays are immutable.

let a = [1, 2, 3]; // a: [i32; 3]
let mut m = [1, 2, 3]; // m: [i32; 3]

Arrays have type [T; N]. We’ll talk about this T notation in the generics section. The N is a compile-time constant, for the length of the array.

There’s a shorthand for initializing each element of an array to the same value. In this example, each element of a will be initialized to 0:

let a = [0; 20]; // a: [i32; 20]

You can get the number of elements in an array a with a.len():

let a = [1, 2, 3];
println!("a has {} elements", a.len());

You can access a particular element of an array with subscript notation:

let names = ["Graydon", "Brian", "Niko"]; // names: [&str; 3]
println!("The second name is: {}", names[1]);

If you try to use a subscript that is not in the array, you will get an error: array access is bounds-checked at run-time.

Slices

A ‘slice’ is a reference to (or “view” into) another data structure. They are useful for allowing safe, efficient access to a portion of an array without copying. For example, you might want to reference just one line of a file read into memory. By nature, a slice is not created directly, but from an existing variable binding. Slices have a defined length, can be mutable or immutable. Proprio come in Go; Rust ha copiato.

You can use a combo of & and [] to create a slice from various things. The & indicates that slices are similar to references, and the []s, with a range, let you define the length of the slice:

let a = [0, 1, 2, 3, 4];
let complete = &a[..]; // A slice containing all of the elements in a
let middle = &a[1..4]; // A slice of a: just the elements 1, 2, and 3

Slices have type &[T]. We’ll talk about that T when we cover generics.

str

Rust’s str type is the most primitive string type. As an unsized type, it’s not very useful by itself, but becomes useful when placed behind a reference, like &str. As such, we’ll just leave it at that.

Tuple

A tuple is an ordered list of fixed size. Like this:

let x = (1, "hello");

The parentheses and commas form this two-length tuple. Here’s the same code, but with the type annotated:

let x: (i32, &str) = (1, "hello");

You can assign one tuple into another, if they have the same contained types and arity. Tuples have the same arity when they have the same length.

let mut x = (1, 2); // x: (i32, i32)
let y = (2, 3); // y: (i32, i32)
x = y;

You can access the fields in a tuple through a destructuring let. Here’s an example:

let (x, y, z) = (1, 2, 3);
println!("x is {}", x);

Remember when I said the left-hand side of a let statement was more powerful than just assigning a binding? Here we are. We can put a pattern on the left-hand side of the let, and if it matches up to the right-hand side, we can assign multiple bindings at once. In this case, let “destructures” or “breaks up” the tuple, and assigns the bits to three bindings.

This pattern is very powerful, and we’ll see it repeated more later.

You can disambiguate a single-element tuple from a value in parentheses with a comma:

(0,); // single-element tuple
(0); // zero in parentheses

Indicizzazione delle tuple

You can also access fields of a tuple with indexing syntax:

let tuple = (1, 2, 3);
let x = tuple.0;
let y = tuple.1;
let z = tuple.2;
println!("x is {}", x);

Like array indexing, it starts at zero, but unlike array indexing, it uses a ., rather than []s.

Funzioni

Functions also have a type! They look like this:

fn foo(x: i32) -> i32 { x }
let x: fn(i32) -> i32 = foo;

In this case, x is a ‘function pointer’ to a function that takes an i32 and returns an i32.

Vediamo se ho capito:

fn foo(x: i32) -> i32 
    { x }

fn main() {
    let x: fn(i32) -> i32 = foo;

    let y = x(42);
    println!("y is {}", y);
}

rs5-0

Nota (forse) solo per me: la prima versione era questa:

fn main() {
    fn foo(x: i32) -> i32 
        { x }
    let x: fn(i32) -> i32 = foo;

    let y = x(42);
    println!("y is {}", y);
}

che vuol dire (e se è già stato detto ma me lo sono perso) che le funzioni possono essere annidate :grin: da indagare, prossimamente :grin:

:mrgreen:

Marvin Minsky – un po’ di cinguettii

CZqXlDSWEAAgYpE
Twitter è il mio social media preferito; pare abbia difficoltà a emergere | crescere | soppravcivere, peccato e davvero non capisco perché.
Ecco qualche link su Marvin Minsky, ce ne sono tanti, mi limito a due tweeps particolarmente attivi sull’argomento.

Rainer Joswig:

CSAIL at MIT

E poi Luis Souto Graña: Marvin Minsky declara: “tipado dinamista hasta la sepultura”.
Non è Twitter ma c’è anche questo: Hacker koan, Uncarved_block.

:mrgreen:

Aggiornamento per Visto nel Web

mms0I post di gran lunga più popolari del blog sono quelli della telenovela “Visto nel Web“.
Sono anche facili da compilare, ci metto dentro quasi tutto quello che vedo, spesso non leggendo con l’attenzione che sarebbe necessaria (vale a dire “lo faccio poi”, cioè “mai”). E pensare che a volte non basta leggere, bisogna studiare, provare, rifare… OK, manca il tempo.
Recentemente Nicola Losito, kOoLiNuS, commenta:

ma ci vuole un mese per leggere tutte le risorse linkate

e

[una] maggiore “classificazione” dei link sarebbe più comoda per noi che leggiamo

Ha ragione. Allora, anche se attualmente questi post vengono compilati quasi automaticamente credo sia doveroso aggiungere le categorie.

Quello a cui sto pensando è di ottenere (con un minimo incremento di lavoro da parte mia) qualcosa come:

C++11 threads, affinity and hyperthreading
#:linguaggi
::: Eli Bendersky

ReactOS, il ritorno di Windows Xp, o forse no…
#:sistemi operativi
::: Socialandtech

Silicon Valley braces itself for a fall: ‘There’ll be a lot of blood’
#:economia
::: the Guardian

Si tratta in altri termini di introdurre gli hashtags. Siccome cito spesso Twitter adotto una sintassi mia, #: invece del semplice #.
Non dovrebbe essere troppo difficile, anzi basta costruire un dizionario per lo script Python che legge il file delle categorie così formato:

#:bug : bug
#:eco : economia
#:ditte : ditte
#:fro : frodi
#:func : programmazione funzionale
#:fut : previsioni per il futuro
#:gos : gossip, pettegolezzi
#:hard : hardware
#:inno : innoazioni
#:intn : internet
#:lang : linguaggi di programmazione
#:lisp : lisp e derivati
#:news : novità
#os : sistemi operativi
#:sic : sicurezza
#:spam : spam
#:spy : spionaggio
#:web : web

e inserisce le stringhe richieste nel file html.
Il lavoro principale è creare questa lista, benvenuti i suggerimenti; ogni voce potrà averne zero o più.
Tutto questo è fin d’ora messo tra le cose da fare, urgenti ma non urgentissimissime. E ho il file categ aperto, da riempire :roll: :grin:

:mrgreen:

Marvin Minsky

marvin
Non ho parole, riporto quelle di altri:

RIP.

Approssimazioni su numeri enormemente grandi – 1

bb7Cosa non si trova su Twitter, per esempio questo whistleblower: I tried nodeJS today.
Sarà vero? provo:

a0

:oops: Uh! e pensare che il Prossimo Presidente, meglio di Silvio [1] dice che “All numbers must be strictly greater than 1 million. The small stuff is inconsequential to us.” (cit.), qui.

Secondo me è il caso di verificare con qualche altro linguaggio, dei soliti.

a1

:grin: OK, Python promosso.

a2

:grin: ovviamente, tutto come previsto.

a3

:grin: certo, anche il mio vecchio amico.

E per i linguaggi seri—- quelli che si usavano una volta, quelli compilati, quelli che fanno attenzione al tipo di dato? Per esempio (nostàlgia here) il Fortran, quello nuovo, nèh :wink:
Beh… ho dovuto chiedere aiuto, la mia memoria…, per fortuna c’è Stack Overflow: Fortran: the largest and the smallest integer.

program integerkinds
    use iso_fortran_env
    implicit none

    integer :: i
    integer(kind=int8)  :: i8
    integer(kind=int16) :: i16
    integer(kind=int32) :: i32
    integer(kind=int64) :: i64

    integer(kind=selected_int_kind(6)) :: j6
    integer(kind=selected_int_kind(15)):: j15

    print *,'Default:'
    print *, huge(i)
    print *,'Int8:'
    print *, huge(i8)
    print *,'Int16:'
    print *, huge(i16)
    print *,'Int32:'
    print *, huge(i32)
    print *,'Int64:'
    print *, huge(i64)

    print *,''

    print *,'Selected Integer Kind 6:'
    print *, huge(j6)

    print *,'Selected Integer Kind 15:'
    print *, huge(j15)

end program integerkinds

a4

Allora tornando al dunque: siamo fuori range, nessuna speranza con gli interi. Bisogna accontentarci dell’approssimazione che otteniamo con i float.

program approx

    real(kind=4) :: p4, g4
    real(kind=8) :: p8, g8
    real(kind=16) :: p16, g16
    logical res

    p4 = 9999999999999999999.
    g4 = 10000000000000000000.
    res = p4 == g4
    print *, p4, " == ", g4, " -> " , res
    print *

    p8 = 9999999999999999999.
    g8 = 10000000000000000000.
    res = p8 == g8
    print *, p8, " == ", g8, " -> " , res
    print *

    p16 = 9999999999999999999.
    g16 = 10000000000000000000.
    res = p16 == g16
    print *, p16, " == ", g16, " -> " , res
    print *

end

a5

No, non c’è speranza. Sempre che questi numeri (trumpici) servano davvero :roll:

Mi sa che serve un’altra puntata, prossimamente, forse :wink:


1. dai non si può essere meglio, diciamo “ottimissimissimo come”.

:mrgreen:

Iscriviti

Ricevi al tuo indirizzo email tutti i nuovi post del sito.

Segui assieme ad altri 89 follower