Category Archives: Julia

Julia – 15 – stringhe – 1

Continuo da qui, copio qui.

Strings are finite sequences of characters. Of course, the real trouble comes when one asks what a character is. The characters that English speakers are familiar with are the letters A, B, C, etc., together with numerals and common punctuation symbols. These characters are standardized together with a mapping to integer values between 0 and 127 by the ASCII standard. There are, of course, many other characters used in non-English languages, including variants of the ASCII characters with accents and other modifications, related scripts such as Cyrillic and Greek, and scripts completely unrelated to ASCII and English, including Arabic, Chinese, Hebrew, Hindi, Japanese, and Korean. The Unicode standard tackles the complexities of what exactly a character is, and is generally accepted as the definitive standard addressing this problem. Depending on your needs, you can either ignore these complexities entirely and just pretend that only ASCII characters exist, or you can write code that can handle any of the characters or encodings that one may encounter when handling non-ASCII text. Julia makes dealing with plain ASCII text simple and efficient, and handling Unicode is as simple and efficient as possible. In particular, you can write C-style string code to process ASCII strings, and they will work as expected, both in terms of performance and semantics. If such code encounters non-ASCII text, it will gracefully fail with a clear error message, rather than silently introducing corrupt results. When this happens, modifying the code to handle non-ASCII data is straightforward.

There are a few noteworthy high-level features about Julia’s strings:

  • The built-in concrete type used for strings (and string literals) in Julia is String. This supports the full range of Unicode characters via the UTF-8 encoding. (A transcode() function is provided to convert to/from other Unicode encodings.)
  • All string types are subtypes of the abstract type AbstractString, and external packages define additional AbstractString subtypes (e.g. for other encodings). If you define a function expecting a string argument, you should declare the type as AbstractString in order to accept any string type.
  • Like C and Java, but unlike most dynamic languages, Julia has a first-class type representing a single character, called Char. This is just a special kind of 32-bit primitive type whose numeric value represents a Unicode code point.
  • As in Java, strings are immutable: the value of an AbstractString object cannot be changed. To construct a different string value, you construct a new string from parts of other strings.
  • Conceptually, a string is a partial function from indices to characters: for some index values, no character value is returned, and instead an exception is thrown. This allows for efficient indexing into strings by the byte index of an encoded representation rather than by a character index, which cannot be implemented both efficiently and simply for variable-width encodings of Unicode strings.

A Char value represents a single character: it is just a 32-bit primitive type with a special literal representation and appropriate arithmetic behaviors, whose numeric value is interpreted as a Unicode code point. Here is how Char values are input and shown:

You can convert a Char to its integer value, i.e. code point, easily:

On 32-bit architectures, typeof(ans) will be Int32. You can convert an integer value back to a Char just as easily:

Not all integer values are valid Unicode code points, but for performance, the Char() conversion does not check that every character value is valid. If you want to check that each converted value is a valid code point, use the isvalid() function:

As of this writing, the valid Unicode code points are U+00 through U+d7ff and U+e000 through U+10ffff. These have not all been assigned intelligible meanings yet, nor are they necessarily interpretable by applications, but all of these values are considered to be valid Unicode characters.

You can input any Unicode character in single quotes using \u followed by up to four hexadecimal digits or \U followed by up to eight hexadecimal digits (the longest valid value only requires six):

Julia uses your system’s locale and language settings to determine which characters can be printed as-is and which must be output using the generic, escaped \u or \U input forms. In addition to these Unicode escape forms, all of C’s traditional escaped input forms can also be used:

You can do comparisons and a limited amount of arithmetic with Char values:


Julia – 14 – numeri complessi e razionali – 2

Continuo da qui, copio qui.

Numeri razionali
Julia has a rational number type to represent exact ratios of integers. Forse non tutti sanni che Julia viene dalla prestigiosa amiglia del Lisp 😁 Rationals are constructed using the // operator:

If the numerator and denominator of a rational have common factors, they are reduced to lowest terms such that the denominator is non-negative:

Si possono ovviamente usare spazi e variabili

This normalized form for a ratio of integers is unique, so equality of rational values can be tested by checking for equality of the numerator and denominator. The standardized numerator and denominator of a rational value can be extracted using the numerator() and denominator() functions:

Direct comparison of the numerator and denominator is generally not necessary, since the standard arithmetic and comparison operations are defined for rational values:

Nota per me: gli spazi nel razionale sono una pessima idea.

Rationals can be easily converted to floating-point numbers:

Conversion from rational to floating-point respects the following identity for any integral values of a and b, with the exception of the case a == 0 and b == 0:

Constructing infinite rational values is acceptable:

Trying to construct a NaN rational value, however, is not:

As usual, the promotion system makes interactions with other numeric types effortless:

Non so voi ma per me Julia rockz! 🚀


Julia – 13 – numeri complessi e razionali – 1

Continuo da qui, copio qui.

Julia ships with predefined types representing both complex and rational numbers, and supports all standard Mathematical Operations and Elementary Functions on them. Conversion and Promotion [prossimamente] are defined so that operations on any combination of predefined numeric types, whether primitive or composite, behave as expected.

Numeri complessi
The global constant im is bound to the complex number i, representing the principal square root of -1. It was deemed harmful to co-opt the name i for a global constant, since it is such a popular index variable name. Since Julia allows numeric literals to be juxtaposed with identifiers as coefficients, this binding suffices to provide convenient syntax for complex numbers, similar to the traditional mathematical notation:

You can perform all the standard arithmetic operations with complex numbers:

The promotion mechanism ensures that combinations of operands of different types just work:

Note that 3/4im == 3/(4*im) == -(3/4*im), since a literal coefficient binds more tightly than division.

Standard functions to manipulate complex values are provided:

As usual, the absolute value (abs()) of a complex number is its distance from zero. abs2() gives the square of the absolute value, and is of particular use for complex numbers where it avoids taking a square root. angle() returns the phase angle in radians (also known as the argument or arg function). The full gamut of other Elementary Functions is also defined for complex numbers:

Note that mathematical functions typically return real values when applied to real numbers and complex values when applied to complex numbers. For example, sqrt() behaves differently when applied to -1 versus -1 + 0im even though -1 == -1 + 0im:

The literal numeric coefficient notation does not work when constructing a complex number from variables. Instead, the multiplication must be explicitly written out:

However, this is not recommended; Use the complex() function instead to construct a complex value directly from its real and imaginary parts:

This construction avoids the multiplication and addition operations.

Inf and NaN propagate through complex numbers in the real and imaginary parts of a complex number:


Julia – 12 – operazioni matematiche e funzioni elementari – 3

Continuo da qui, copio qui.

Precedenze tra operatori
Julia applies the following order of operations, from highest precedence to lowest:

Category       Operators
Syntax	       . followed by ::
Exponentiation ^
Fractions      //
Multiplication * / % & \
Bitshifts      << >> >>>
Addition       + - | ⊻
Syntax	       : .. followed by |>
Comparisons    > < >= <= == === != !== <:
Control flow   && followed by || followed by ?
Assignments    = += -= *= /= //= \= ^= ÷= %= |= &= ⊻= <<= >>= >>>=

For a complete list of every Julia operator’s precedence, see the top of this file.
Uh! 😁 Fantastico il linguaggio con cui è scritto Julia: Scheme, cioè Lisp (una variante del) 🚀

You can also find the numerical precedence for any given operator via the built-in function Base.operator_precedence, where higher numbers take precedence:

Conversioni numeriche
Julia supports three forms of numerical conversion, which differ in their handling of inexact conversions.

  • The notation T(x) or convert(T, x) converts x to a value of type T.
    ° If T is a floating-point type, the result is the nearest representable value, which could be positive or negative infinity.
    ° If T is an integer type, an InexactError is raised if x is not representable by T.
  • x % T converts an integer x to a value of integer type T congruent to x modulo 2^n, where n is the number of bits in T. In other words, the binary representation is truncated to fit.
  • The Rounding functions take a type T as an optional argument. For example, round(Int, x) is a shorthand for Int(round(x)).

The following examples show the different forms.

See Conversion and Promotion [prossimamente] for how to define your own conversions and promotions.

Funzioni di arrotondamento

Function	Description                    Return type
round(x)        round x to the nearest integer typeof(x)
round(T, x)     round x to the nearest integer T
floor(x)        round x towards -Inf           typeof(x)
floor(T, x)     round x towards -Inf           T
ceil(x)	        round x towards +Inf               typeof(x)
ceil(T, x)      round x towards +Inf           T
trunc(x)        round x towards zero           typeof(x)
trunc(T, x)     round x towards zero           T

Funzioni di divisione

Function    Description
div(x,y)    truncated division; quotient rounded towards zero
fld(x,y)    floored division; quotient rounded towards -Inf
cld(x,y)    ceiling division; quotient rounded towards +Inf
rem(x,y)    remainder; satisfies x == div(x,y)*y + rem(x,y); sign matches x
mod(x,y)    modulus; satisfies x == fld(x,y)*y + mod(x,y); sign matches y
mod1(x,y)   mod() with offset 1; returns r∈(0,y] for y>0 or r∈[y,0) for
            y<0, where mod(r, y) == mod(x, y)
mod2pi(x)   modulus with respect to 2pi; 0 <= mod2pi(x)   < 2pi
divrem(x,y) returns (div(x,y),rem(x,y))
fldmod(x,y) returns (fld(x,y),mod(x,y))
gcd(x,y...) greatest positive common divisor of x, y,...
lcm(x,y...) least positive common multiple of x, y,...

Potenze, logaritmi e radici

Function       Description
sqrt(x), √x    square root of x
cbrt(x), ∛x    cube root of x
hypot(x,y)     hypotenuse of right-angled triangle with
               other sides of length x and y
exp(x)         natural exponential function at x
expm1(x)       accurate exp(x)-1 for x near zero
ldexp(x,n)     x*2^n computed efficiently for integer values of n
log(x)         natural logarithm of x
log(b,x)       base b logarithm of x
log2(x)        base 2 logarithm of x
log10(x)       base 10 logarithm of x
log1p(x)       accurate log(1+x) for x near zero
exponent(x)    binary exponent of x
significand(x) binary significand (a.k.a. mantissa) of 
               a floating-point number x

For an overview of why functions like hypot(), expm1(), and log1p() are necessary and useful, see John D. Cook’s excellent pair of blog posts on the subject: expm1, log1p, erfc, and hypot.

Nota: codici Unicode U+221A, U+221B. Io li cerco (se costretto a usarli) da FileFormat.Info.

Funzioni trigonometriche e iperboliche
All the standard trigonometric and hyperbolic functions are also defined:

sin    cos    tan    cot    sec    csc
sinh   cosh   tanh   coth   sech   csch
asin   acos   atan   acot   asec   acsc
asinh  acosh  atanh  acoth  asech  acsch
sinc   cosc   atan2

These are all single-argument functions, with the exception of atan2, which gives the angle in radians between the x-axis and the point specified by its arguments, interpreted as x and y coordinates.

Additionally, sinpi(x) and cospi(x) are provided for more accurate computations of sin(pi*x) and cos(pi*x) respectively.

In order to compute trigonometric functions with degrees instead of radians, suffix the function with d. For example, sind(x) computes the sine of x where x is specified in degrees. The complete list of trigonometric functions with degree variants is:

sind   cosd   tand   cotd   secd   cscd
asind  acosd  atand  acotd  asecd  acscd

Funzioni speciali

Function   Description
gamma(x)   gamma function at x
lgamma(x)  accurate log(gamma(x)) for large x
lfact(x)   accurate log(factorial(x)) 
           for large x; same as lgamma(x+1) 
           for x > 1, zero otherwise
beta(x,y)  beta function at x,y
lbeta(x,y) accurate log(beta(x,y)) for large x or y


Julia – 11 – operazioni matematiche e funzioni elementari – 2

Continuo da qui, copio qui.

Operatore . (punto, dot) vettorializzato
For every binary operation like ^, there is a corresponding “dot” operation .^ that is automatically defined to perform ^ element-by-element on arrays. For example, [1,2,3] ^ 3 is not defined, since there is no standard mathematical meaning to “cubing” an array, but [1,2,3] .^ 3 is defined as computing the elementwise (or “vectorized”) result [1^3, 2^3, 3^3]. Similarly for unary operators like ! or , there is a corresponding .√ that applies the operator elementwise.

Nota: è U+221A, square root, e noi vecchi usiamo sqrt(), voi fate voi 😜

More specifically, a .^ b is parsed as the “dot” call (^).(a,b), which performs a broadcast operation: it can combine arrays and scalars, arrays of the same size (performing the operation elementwise), and even arrays of different shapes (e.g. combining row and column vectors to produce a matrix). Moreover, like all vectorized “dot calls,” these “dot operators” are fusing. For example, if you compute 2 .* A.^2 .+ sin.(A) (or equivalently @. 2A^2 + sin(A), using the @. macro) for an array A, it performs a single loop over A, computing 2a^2 + sin(a) for each element of A. In particular, nested dot calls like f.(g.(x)) are fused, and “adjacent” binary operators like x .+ 3 .* x.^2 are equivalent to nested dot calls (+).(x, (*).(3, (^).(x, 2))).

Furthermore, “dotted” updating operators like a .+= b (or @. a += b) are parsed as a .= a .+ b, where .= is a fused in-place assignment operation (see the dot syntax documentation [prossimamente]).

Note the dot syntax is also applicable to user-defined operators. For example, if you define ⊗(A,B) = kron(A,B) to give a convenient infix syntax A ⊗ B for Kronecker products (kron), then [A,B] .⊗ [C,D] will compute [A⊗C, B⊗D] with no additional coding.

Uhmmm… tante cose qui che andranno spiegate in futuro. per adesso: mystero 😯

Comparazioni numeriche
Standard comparison operations are defined for all the primitive numeric types:

Operator Name
==       equality
!=, ≠    inequality
<        less than
<=, ≤    less than or equal to 
>        greater than
>=, ≥	 greater than or equal to

Codici Unicode: U+2260, U+2264, U+2265; naturalmente noi vecchi… 😜

Integers are compared in the standard manner – by comparison of bits. Floating-point numbers are compared according to the IEEE 754 standard:

  • Finite numbers are ordered in the usual manner.
  • Positive zero is equal but not greater than negative zero.
  • Inf is equal to itself and greater than everything else except NaN.
  • -Inf is equal to itself and less then everything else except NaN.
  • NaN is not equal to, not less than, and not greater than anything, including itself.

The last point is potentially surprising and thus worth noting:

and can cause especial headaches with Arrays:

Julia provides additional functions to test numbers for special values, which can be useful in situations like hash key comparisons:

Function      Tests if
isequal(x, y) x and y are identical
isfinite(x)   x is a finite number
isinf(x)      x is infinite
isnan(x)      x is not a number

isequal() considers NaNs equal to each other:

isequal() can also be used to distinguish signed zeros:

Mixed-type comparisons between signed integers, unsigned integers, and floats can be tricky. A great deal of care has been taken to ensure that Julia does them correctly.

For other types, isequal() defaults to calling ==(), so if you want to define equality for your own types then you only need to add a ==() method. If you define your own equality function, you should probably define a corresponding hash() method to ensure that isequal(x,y) implies hash(x) == hash(y). Anche qui cose che saranno approfondite in futuro.

Concatenare comparazioni
Unlike most languages, with the notable exception of Python, comparisons can be arbitrarily chained:

Chaining comparisons is often quite convenient in numerical code. Chained comparisons use the && operator for scalar comparisons, and the & operator for elementwise comparisons, which allows them to work on arrays. For example, 0 .< A .< 1 gives a boolean array whose entries are true where the corresponding elements of A are between 0 and 1.

The middle expression is only evaluated once, rather than twice as it would be if the expression were written as v(1) < v(2) && v(2) <= v(3). However, the order of evaluations in a chained comparison is undefined. It is strongly recommended not to use expressions with side effects (such as printing) in chained comparisons. If side effects are required, the short-circuit && operator should be used explicitly (see Short-Circuit Evaluation [prossimamente]).

Funzioni elementari
Julia provides a comprehensive collection of mathematical functions and operators. These mathematical operations are defined over as broad a class of numerical values as permit sensible definitions, including integers, floating-point numbers, rationals, and complex numbers, wherever such definitions make sense.

Moreover, these functions (like any Julia function) can be applied in “vectorized” fashion to arrays and other collections with the dot syntax f.(A), e.g. sin.(A) will compute the sine of each element of an array A.


Julia – 10 – operazioni matematiche e funzioni elementari – 1

Continuo da qui, copio qui.

Julia provides a complete collection of basic arithmetic and bitwise operators across all of its numeric primitive types, as well as providing portable, efficient implementations of a comprehensive collection of standard mathematical functions.

Operatori aritmetici
The following arithmetic operators are supported on all primitive numeric types:

Expr. Name           Description
+x    unary plus     the identity operation
-x    unary minus    maps values to their additive inverses
x + y binary plus    performs addition
x - y binary minus   performs subtraction
x * y times          performs multiplication
x / y divide         performs division
x \ y inverse divide equivalent to y / x
x ^ y power          raises x to the yth power
x % y remainder      equivalent to rem(x,y)

as well as the negation on Bool types:

Expr. Name           Description
!x    negation       changes true to false and vice versa

Julia’s promotion system makes arithmetic operations on mixtures of argument types “just work” naturally and automatically. See Conversion and Promotion [prossimamente] for details of the promotion system.

Here are some simple examples using arithmetic operators:

By convention, we tend to space operators more tightly if they get applied before other nearby operators. For instance, we would generally write -x + 2 to reflect that first x gets negated, and then 2 is added to that result. A differenza del tutorial io tendo a lasciare spazi anche per * e /; inoltre mi piace poco \ (divisione inversa).

Operatori bitwise
The following bitwise operators are supported on all primitive integer types:

Expr.   Name
~x      bitwise not
x & y   bitwise and
x | y   bitwise or
x ⊻ y   bitwise xor (exclusive or)
x >>> y logical shift right
x >> y  arithmetic shift right
x << y  logical/arithmetic shift left

Notare l’uso di codice Unicode 22BB e sì, si chiama proprio xor. Ma non è più semplice scrivere “xor()“?

Here are some examples with bitwise operators:

Nota: forse è utile usare bits per visualizzare questi operatori

Inoltre, sempre a chiarimento degli operatori sui bits si può usare parse():

Operatori che aggiornano
Every binary arithmetic and bitwise operator also has an updating version that assigns the result of the operation back into its left operand. The updating version of the binary operator is formed by placing a = immediately after the operator. For example, writing x += 3 is equivalent to writing x = x + 3:

The updating versions of all the binary arithmetic and bitwise operators are:

+= -= *= /= \= ÷= %= ^= &= |= ⊻= >>>= >>= <<=

Note: An updating operator rebinds the variable on the left-hand side. As a result, the type of the variable may change.


Julia – 9 – numeri interi e floating-point – 6

Continuo da qui, copio qui.

Sono sempre sulla precisione arbitraria; ho installato (non so quanto bene, Ubuntu insiste con quella vecchia di diverse versioni) l’ultima versione per correggere gli errori dovuti al codice del tutorial troppo aggiornato.
Torno quindi ai BigFloat.

The default precision (in number of bits of the significand) and rounding mode of BigFloat operations can be changed globally by calling setprecision() and setrounding(), and all further calculations will take these changes in account. Alternatively, the precision or the rounding can be changed only within the execution of a particular block of code by using the same functions with a do block:

Coefficienti numerici letterali
To make common numeric formulas and expressions clearer, Julia allows variables to be immediately preceded by a numeric literal, implying multiplication. This makes writing polynomial expressions much cleaner:

It also makes writing exponential functions more elegant:

uepp! 😯
The precedence of numeric literal coefficients is the same as that of unary operators such as negation. So 2^3x is parsed as 2^(3x), and 2x^3 is parsed as 2*(x^3).

Non mi ricordo di altri linguaggi che si comportino in questo modo; se si è troppo abituati al vecchio potrebbero esserci errori logici (dell’umano).

Numeric literals also work as coefficients to parenthesized expressions:

Additionally, parenthesized expressions can be used as coefficients to variables, implying multiplication of the expression by the variable:

Neither juxtaposition of two parenthesized expressions, nor placing a variable before a parenthesized expression, however, can be used to imply multiplication:

Both expressions are interpreted as function application: any expression that is not a numeric literal, when immediately followed by a parenthetical, is interpreted as a function applied to the values in parentheses (see Functions [prossimamente] for more about functions). Thus, in both of these cases, an error occurs since the left-hand value is not a function.

The above syntactic enhancements significantly reduce the visual noise incurred when writing common mathematical formulae. Note that no whitespace may come between a numeric literal coefficient and the identifier or parenthesized expression which it multiplies.

Conflitti di sintassi
Juxtaposed literal coefficient syntax may conflict with two numeric literal syntaxes: hexadecimal integer literals and engineering notation for floating-point literals. Here are some situations where syntactic conflicts arise:

  • The hexadecimal integer literal expression 0xff could be interpreted as the numeric literal 0 multiplied by the variable xff.
  • The floating-point literal expression 1e10 could be interpreted as the numeric literal 1 multiplied by the variable e10, and similarly with the equivalent E form.

In both cases, we resolve the ambiguity in favor of interpretation as a numeric literals:

  • Expressions starting with 0x are always hexadecimal literals.
  • Expressions starting with a numeric literal followed by e or E are always floating-point literals.

zero e one letterali
Julia provides functions which return literal 0 and 1 corresponding to a specified type or the type of a given variable.

Function Description
zero(x)  Literal zero of type x or type of variable x
one(x)   Literal one of type x or type of variable x

These functions are useful in numeric comparisons to avoid overhead from unnecessary type conversion.


Julia – 8 – numeri interi e floating-point – 5

Continuo da qui, copio qui.

Aritmetica a precisione arbitraria
To allow computations with arbitrary-precision integers and floating point numbers, Julia wraps the GNU Multiple Precision Arithmetic Library (GMP) and the GNU MPFR Library, respectively. The BigInt and BigFloat types are available in Julia for arbitrary precision integer and floating point numbers respectively.

Constructors exist to create these types from primitive numerical types, and parse() can be used to construct them from AbstractStrings. Once created, they participate in arithmetic with all other numeric types thanks to Julia’s type promotion and conversion mechanism [prossimamente]:

However, type promotion between the primitive types above and BigInt / BigFloat is not automatic and must be explicitly stated.

The default precision (in number of bits of the significand) and rounding mode of BigFloat operations can be changed globally by calling setprecision() and setrounding(), and all further calculations will take these changes in account. Alternatively, the precision or the rounding can be changed only within the execution of a particular block of code by using the same functions with a do block.

OOPS!, ottengo un errore perché sto usando una versione vecchia. Aggiorno; cioè no, avendo installato Julia via apt di Ununtu non vede versioni più recenti. Devo disinstallarlo e reinstallarlo nel modo indicato dal sito di Julia stesso. Prossimamente 😜


Julia – 7 – numeri interi e floating-point – 4

Continuo da qui, copio qui.

Epsilon della macchina
Most real numbers cannot be represented exactly with floating-point numbers, and so for many purposes it is important to know the distance between two adjacent representable floating-point numbers, which is often known as machine epsilon.

Julia provides eps(), which gives the distance between 1.0 and the next larger representable floating-point value:

These values are 2.0^-23 and 2.0^-52 as Float32 and Float64 values, respectively. The eps() function can also take a floating-point value as an argument, and gives the absolute difference between that value and the next representable floating point value. That is, eps(x) yields a value of the same type as x such that x + eps(x) is the next representable floating-point value larger than x:

The distance between two adjacent representable floating-point numbers is not constant, but is smaller for smaller values and larger for larger values. In other words, the representable floating-point numbers are densest in the real number line near zero, and grow sparser exponentially as one moves farther away from zero. By definition, eps(1.0) is the same as eps(Float64) since 1.0 is a 64-bit floating-point value.

Julia also provides the nextfloat() and prevfloat() functions which return the next largest or smallest representable floating-point number to the argument respectively:

This example highlights the general principle that the adjacent representable floating-point numbers also have adjacent binary integer representations.

Modi di arrotondamento
If a number doesn’t have an exact floating-point representation, it must be rounded to an appropriate representable value, however, if wanted, the manner in which this rounding is done can be changed according to the rounding modes presented in the IEEE 754 standard.

OOPS! ma ecco un warning: This feature is still experimental, and may give unexpected or incorrect values. E non ho installato l’ultima versione, devo ponderare se…

per intanto il risultato voluto lo ottengo con

The default mode used is always RoundNearest, which rounds to the nearest representable value, with ties rounded towards the nearest value with an even least significant bit.

Warning: Rounding is generally only correct for basic arithmetic functions (+(), -(), *(), /() and sqrt()) and type conversion operations. Many other functions assume the default RoundNearest mode is set, and can give erroneous results when operating under other rounding modes.

Background e riferimenti
Floating-point arithmetic entails many subtleties which can be surprising to users who are unfamiliar with the low-level implementation details. However, these subtleties are described in detail in most books on scientific computation, and also in the following references:


Julia – 6 – numeri interi e floating-point – 3

Continuo da qui, copio qui.

Numeri floating-point
Literal floating-point numbers are represented in the standard formats:

The above results are all Float64 values. Literal Float32 values can be entered by writing an f in place of e:

Values can be converted to Float32 easily:

Hexadecimal floating-point literals are also valid, but only as Float64 values:

da chiarire il misterioso p.

Half-precision floating-point numbers are also supported (Float16), but they are implemented in software and use Float32 for calculations.

Nota: il formato cambia nelle versioni successive a quella da me installata.

The underscore _ can be used as digit separator:

Zero floating-point
Floating-point numbers have two zeros, positive zero and negative zero. They are equal to each other but have different binary representations, as can be seen using the bits function:

in effetti cambia solo il bit del segno.

Valori floating-point speciali
There are three specified standard floating-point values that do not correspond to any point on the real number line:

Float16 Float32 Float64 Name                Description
Inf16   Inf32   Inf     positive infinity   a value greater than all
                                            finite floating-point values
-Inf16  -Inf32  -Inf    negative infinity   a value less than all finite
                                            floating-point values
NaN16   NaN32   NaN     not a number        a value not == to any 
                                            floating-point value 
                                            (including itself)

For further discussion of how these non-finite floating-point values are ordered with respect to each other and other floats, see Numeric Comparisons [prossimamente]. By the IEEE 754 standard, these floating-point values are the results of certain arithmetic operations:

The typemin() and typemax() functions also apply to floating-point types: