LEVIATHAN vd52e79c4 · d52e79c486

Standard Library

class float

A 64-bit IEEE 754 floating-point number (binary64).

since 0.1.0-alpha.1linuxwindowswasm

Overview

A literal with a decimal point (2.0) is a float. A float prints its shortest round-trip digits in scientific notation (2.0e0, 3.0000000000000004e-1), and the special values print as NaN, Infinity and -Infinity. Arithmetic follows IEEE 754: an operation such as the square root of a negative number produces NaN, and an overflow produces an infinity, instead of throwing. Use isNaN and isInfinite to test for them; a comparison such as x == float::NaN is never true.

Mixed arithmetic is promoted: an int combined with a float gives a float. To go back to an int call toInt, which truncates. The narrower formats float8, float16 and float32 are reached with toFloat8, toFloat16 and toFloat32.

Description

float is an IEEE 754 binary64 number and the type of any literal with a decimal point. It is a value type. A literal may carry an exponent in the printed form, 1.0e3 or 2.5e-7; the point is required, so 1e3 is not a float literal.

A float prints as the shortest decimal that reads back as exactly the same value, always in scientific notation: one digit, a point, at least one more digit, e and the decimal exponent, with - when the exponent is negative and no + or padding. So 0.1 + 0.2 prints 3.0000000000000004e-1, 1.5 prints 1.5e0 and 10.0.pow(300.0) prints 1.0e300. Zero prints as 0.0e0 and negative zero as -0.0e0. Infinities print as Infinity and -Infinity, and every NaN prints as NaN, whatever its internal bits. The text is the same on every engine and platform and never depends on a locale, and string.toFloat() reads it back to the identical value.

Rounding, printing and special values

use io::console;

float x = 3.5;
console.writeln(x);
console.writeln(x.floor());
console.writeln(x.ceil());
console.writeln(x.round());
console.writeln((-2.5).round());
console.writeln(x.trunc());
console.writeln((-3.99).toInt());
console.writeln(2.0.sqrt());
console.writeln((-1.0).sqrt());
console.writeln(0.1 + 0.2 == 0.3);
console.writeln(0.1 + 0.2);
console.writeln(1000000.0 * 1000000.0);
float zero = 0.0;
console.writeln(1.0 / zero);
console.writeln(-1.0 / zero);
console.writeln(zero / zero);
console.writeln(-zero);
try {
    console.writeln((1.0 / zero).toInt());
} catch (RuntimeException e) {
    console.writeln("caught: ${e.message}");
}
3.5e0
3.0e0
4.0e0
4.0e0
-3.0e0
3.0e0
-3
1.4142135623730951e0
NaN
false
3.0000000000000004e-1
1.0e12
Infinity
-Infinity
NaN
-0.0e0
caught: float is not finite or out of int64 range for toInt()

Rules

  • Arithmetic follows IEEE 754. Division by zero gives infinity (or NaN for 0.0 / 0.0) rather than throwing.
  • round() rounds halves away from zero. sqrt() of a negative number is NaN, not an error.
  • toInt() truncates toward zero. It throws a catchable RuntimeException for NaN, an infinity or a value outside the int range.
  • A bare == between two floats is the IEEE operator: NaN == NaN is false, and -0.0 == 0.0 is true.
  • Where equality is derived or a value is used as a key, floats compare by the canonical relation instead: every NaN equals every NaN, and -0.0 equals 0.0. That relation applies to the == a struct gets automatically, to Map keys and Set elements, to == on arrays, maps and sets (their elements compare by it), and to match arms. canonEq is the same relation as a method.
  • float::Infinity is positive infinity (-float::Infinity the negative one), beside the NaN constant float::NaN. A comptime value that is not finite is written back as one of these three spellings, so --expand output is valid source.
  • A match arm can test for NaN with float::NaN.
  • If you write your own == for a struct, it means exactly what you wrote: floats inside it compare with the IEEE operators.
  • bits() returns the raw 64-bit pattern as an int, and float::fromBits(n) builds a float from one. A pattern you construct round-trips exactly. The bits of a NaN produced by arithmetic are not specified.
  • toFixed() writes the same shortest digits in fixed notation, with no exponent: 1.5e-7.toFixed() is 0.00000015, and a whole number keeps .0 (1.0, -0.0), so 1.0e300.toFixed() is 303 characters. toFixed(places) rounds those digits to places fractional digits, half to even like decimal.round, and always writes exactly places of them (1.005.toFixed(2) is 1.00, 2.5.toFixed(0) is 2 with no point); a negative value that rounds to zero keeps its sign (-0.00). A negative places throws a RuntimeException. The infinities and NaN print as in toString(). Every sized float has both methods, using its own format's digits.
  • toFixed works from the shortest digits, never the exact binary value, and writes zeros past them. 0.1.toFixed(20) is 0.10000000000000000000, and a float8 holding 1.125, which prints as 1.1e0, gives 1.100 from toFixed(3).
  • string.toFloat() accepts a decimal number with an optional sign, point and exponent (1.5, +1.5, .5, 5., 1e5, 1.5E-3), a hexadecimal float (0x1p3), and exactly the spellings Infinity, +Infinity, -Infinity and NaN. Its result is correctly rounded. It returns None for anything else, including "inf", "nan", whitespace of any kind before or after the number, and a finite spelling too large for a float such as "1e999".

Examples

Fixed notation, and a threshold of the program's own choosing:

toFixed

use io::console;

float x = 0.1 + 0.2;
console.writeln(x);
console.writeln(x.toFixed());
console.writeln(x.toFixed(2));
console.writeln(1.005.toFixed(2));
console.writeln(2.5.toFixed(0));
console.writeln(1.0.toFixed());
console.writeln(1.5e-7.toFixed());
console.writeln((0.0 - 0.004).toFixed(2));
3.0000000000000004e-1
0.30000000000000004
0.30
1.00
2
1.0
0.00000015
-0.00

Canonical equality for NaN, in keys, structs and match:

IEEE equality versus the canonical relation

use io::console;

struct Reading {
    float v = 0.0;
}

void classify(float f) {
    match (f) {
        float::NaN => console.writeln("not a number");
        else => console.writeln("a number");
    }
}

float zero = 0.0;
float nan = zero / zero;
Reading a = Reading(nan);
Reading b = Reading(nan);
console.writeln(nan == nan);
console.writeln(a == b);
console.writeln(zero == -zero);
console.writeln(nan.canonEq(nan));
Map<float, int> m = Map();
m[nan] = 1;
m[nan] = 2;
console.writeln(m.length());
classify(nan);
classify(1.5);
false
true
true
true
1
not a number
a number

Notes

The narrow formats float8, float16 and float32 are described in lang.sized-floats.

Examples

Typical use

use io::console;

float price = 19.99;
float total = price * 3.0;
console.writeln(total);
console.writeln(total.round());
console.writeln(total.toInt());
console.writeln((0.0 - total).abs());
float bad = (0.0 - 1.0).sqrt();
console.writeln(bad.isNaN());
console.writeln("total: ${total}");
5.997e1
6.0e1
59
5.997e1
true
total: 5.997e1

Fields

Infinity

static const float Infinity

Positive infinity: the value an overflowing operation produces (big * big for big = 1.0e300) and that 1.0 / 0.0 gives. It prints as Infinity; negate it for negative infinity. float::NaN is its not-a-number companion.

Examples

use io::console;

console.writeln(float::Infinity);
console.writeln(-float::Infinity);
float big = 1.0e300;
console.writeln(float::Infinity == big * big);
console.writeln(float::Infinity.isInfinite());
console.writeln(float::Infinity > 1.0e308);
Infinity
-Infinity
true
true
true

Methods

abs

@Pure
abs() -> float

The absolute value: this with any minus sign removed.

A NaN stays a NaN.

Returns

this if it is zero or positive, otherwise its negation.

Examples

use io::console;

console.writeln((0.0 - 3.7).abs());
console.writeln(3.7.abs());
console.writeln(float::NaN.abs().isNaN());
3.7e0
3.7e0
true

bits

bits() -> int

The raw IEEE 754 binary64 bit pattern, as an int.

Useful for serialization and for inspecting a value exactly. float::fromBits is the inverse. The bits of a NaN produced by arithmetic (rather than written as float::NaN) are not specified and can differ between engines and targets, so do not compare them.

Returns

The 64 bits of this, reinterpreted as a signed int.

Examples

use io::console;

console.writeln(1.0.bits());
console.writeln(1.0.bits().toHex());
console.writeln(float::fromBits(4611686018427387904));
console.writeln(float::fromBits(1.5.bits()) == 1.5);
4607182418800017408
3ff0000000000000
2.0e0
true

See also: canonEq

canonEq

canonEq(float other) -> bool

Compare two floats under the canonical relation used for struct equality, Map keys and match.

The ordinary == is the IEEE comparison, where NaN is not equal to itself and -0.0 equals 0.0. Under canonEq every NaN equals every other NaN, while -0.0 still equals 0.0. This is also how a struct with a float field decides whether two values are equal.

Parameters

other
The value to compare with.

Returns

true if the two values are the same under the canonical relation.

Examples

use io::console;

float nan = float::NaN;
console.writeln(nan == nan);
console.writeln(nan.canonEq(nan));
console.writeln(1.5.canonEq(1.5));
console.writeln(1.5.canonEq(2.5));
false
true
true
false

See also: isNaN

ceil

@Pure
ceil() -> float

Round up to the nearest whole number that is not less than this.

The result is still a float. Negative numbers round toward zero (-2.5 becomes -2.0).

Returns

The smallest whole-valued float greater than or equal to this.

Examples

use io::console;

console.writeln(2.1.ceil());
console.writeln((0.0 - 2.9).ceil());
console.writeln(5.0.ceil());
3.0e0
-2.0e0
5.0e0

See also: floor, round, trunc

floor

@Pure
floor() -> float

Round down to the nearest whole number that is not greater than this.

The result is still a float; call toInt to get an int. Negative numbers round away from zero (-2.5 becomes -3.0).

Returns

The largest whole-valued float less than or equal to this.

Examples

use io::console;

console.writeln(2.9.floor());
console.writeln((0.0 - 2.1).floor());
console.writeln(5.0.floor());
2.0e0
-3.0e0
5.0e0

See also: ceil, round, trunc

isInfinite

isInfinite() -> bool

Test whether the value is positive or negative infinity.

Infinity results from overflow, for example 10.0.pow(400.0). A NaN is not infinite.

Returns

true if this is Infinity or -Infinity.

Examples

use io::console;

float big = 10.0.pow(400.0);
console.writeln(big);
console.writeln(big.isInfinite());
console.writeln((0.0 - big).isInfinite());
console.writeln(1.0.isInfinite());
console.writeln(float::NaN.isInfinite());
Infinity
true
true
false
false

See also: isNaN

isNaN

@Pure
isNaN() -> bool

Test whether the value is NaN ("not a number").

NaN results from operations such as the square root of a negative number. It is the only value that is not equal to itself, which is why x == float::NaN is useless and isNaN exists.

Returns

true if this is NaN.

Examples

use io::console;

float r = (0.0 - 1.0).sqrt();
console.writeln(r.isNaN());
console.writeln(r == r);
console.writeln(1.0.isNaN());
true
false
false

See also: isInfinite, canonEq

pow

pow(float e) -> float

Raise this to a power.

Follows the C pow function: a result too large to represent is an infinity, and a negative base with a fractional exponent is NaN.

Parameters

e
The exponent.

Returns

this raised to the power e.

Examples

use io::console;

console.writeln(2.0.pow(10.0));
console.writeln(9.0.pow(0.5));
console.writeln(2.0.pow(0.0 - 1.0));
console.writeln(10.0.pow(400.0));
1.024e3
3.0e0
5.0e-1
Infinity

See also: sqrt

round

round() -> float

Round to the nearest whole number, with halves rounded away from zero.

2.5 becomes 3.0 and -2.5 becomes -3.0, as in the C round function; this is not banker's rounding. The result is still a float.

Returns

The nearest whole-valued float.

Examples

use io::console;

console.writeln(2.4.round());
console.writeln(2.5.round());
console.writeln((0.0 - 2.5).round());
console.writeln(3.5.round());
2.0e0
3.0e0
-3.0e0
4.0e0

See also: floor, ceil, trunc

sqrt

@Pure
sqrt() -> float

The square root.

A negative number gives NaN rather than throwing; test the result with isNaN.

Returns

The non-negative square root of this, or NaN if this is negative.

Examples

use io::console;

console.writeln(16.0.sqrt());
console.writeln(2.0.sqrt());
float r = (0.0 - 4.0).sqrt();
console.writeln(r.isNaN());
4.0e0
1.4142135623730951e0
true

See also: pow

toDecimal

toDecimal() -> decimal

Convert the float to the shortest decimal that reads back as the same float.

A float holds a binary fraction, so 0.1 is really 0.1000000000000000055511151231257827…; toDecimal gives 0.1, the fewest digits that convert back to exactly this float (the closest such number when several qualify). That is the number the literal was written as whenever the literal had at most 15 significant digits. The scale is the count of those digits after the point.

Returns

The shortest decimal that converts back to this.

Throws

RuntimeException
float is not finite for toDecimal() for NaN or an infinity, and float out of decimal range for toDecimal() for a magnitude of 10^34 or more.

Examples

use io::console;

console.writeln(0.1.toDecimal());
console.writeln((0.1 + 0.2).toDecimal());
console.writeln(100000000000000000000.0.toDecimal());
console.writeln(2.50.toDecimal().scale());
try {
    decimal d = float::NaN.toDecimal();
    console.writeln(d);
} catch (RuntimeException e) {
    console.writeln("caught: ${e.message}");
}
0.1
0.30000000000000004
100000000000000000000
1
caught: float is not finite for toDecimal()

See also: toFloat, toDecimal

toFixed

toFixed() -> string

Format the number in fixed notation (no exponent), with the same shortest digits toString() prints.

The digits are the fewest that read back as exactly this value; a whole number keeps .0 (1.0, 0.0, -0.0), and a large or small magnitude is written out in full (1.0e300.toFixed() is 303 characters). The infinities are Infinity and -Infinity, and every NaN is NaN.

Returns

The fixed-notation text of this.

Examples

use io::console;

console.writeln(1.5e-7.toFixed());
console.writeln((0.1 + 0.2).toFixed());
console.writeln(1.0.toFixed());
console.writeln((-0.0).toFixed());
console.writeln(1.0e21.toFixed());
console.writeln(float::NaN.toFixed());
0.00000015
0.30000000000000004
1.0
-0.0
1000000000000000000000.0
NaN
toFixed(int places) -> string

Format the number in fixed notation rounded to places fractional digits.

The shortest digits toString() prints are rounded half to even (the mode of decimal.round(int)), so 1.005.toFixed(2) is 1.00 and 2.5.toFixed(0) is 2. Exactly places digits follow the point, and places 0 writes no point. A negative value that rounds to zero keeps its sign: (0.0 - 0.004).toFixed(2) is -0.00. The infinities and NaN print as in toString().

Parameters

places
The number of digits after the point, from 0 to 1000000000.

Returns

The rounded fixed-notation text of this.

Throws

RuntimeException
when places is negative or above 1000000000.

Examples

use io::console;

console.writeln(3.14159.toFixed(2));
console.writeln(1.005.toFixed(2));
console.writeln(2.5.toFixed(0));
console.writeln(1.5.toFixed(3));
console.writeln((0.0 - 0.004).toFixed(2));
console.writeln(9.995.toFixed(2));
try {
    console.writeln(1.5.toFixed(-1));
} catch (RuntimeException e) {
    console.writeln("caught: ${e.message}");
}
3.14
1.00
2
1.500
-0.00
10.00
caught: toFixed: places must not be negative

toFloat16

toFloat16() -> float16

Convert to the 16-bit float16 format (IEEE binary16).

The value is rounded to the nearest representable one, ties to even. The conversion throws when a finite value is too large for the format (the largest finite float16 is 65504); an infinity converts to an infinity and a NaN to the NaN.

Returns

The nearest float16.

Throws

RuntimeException
when this is finite but outside the range of float16.

Examples

use io::console;

float16 a = 0.1.toFloat16();
console.writeln(a.toFloat());
try {
    console.writeln(70000.0.toFloat16());
} catch (RuntimeException e) {
    console.writeln("caught: ${e.message}");
}
9.99755859375e-2
caught: toFloat16: value out of range (max finite 65504)

See also: float16, toFloat8, toFloat32

toFloat32

toFloat32() -> float32

Convert to the 32-bit float32 format (IEEE binary32).

The value is rounded to the nearest representable one, ties to even, so precision beyond about seven decimal digits is lost. The conversion throws when a finite value is too large for the format (the largest finite float32 is about 3.4e38).

Returns

The nearest float32.

Throws

RuntimeException
when this is finite but outside the range of float32.

Examples

use io::console;

float32 a = 0.1.toFloat32();
console.writeln(a.toFloat());
console.writeln(a.toFloat() == 0.1);
console.writeln(a.toFloat().bits() == 0.1.bits());
1.0000000149011612e-1
false
false

See also: float32, toFloat8, toFloat16

toFloat8

toFloat8() -> float8

Convert to the 8-bit float8 format (E4M3).

The value is rounded to the nearest representable one, ties to even. The conversion throws instead of overflowing: float8 has no infinity, so a value beyond its finite range cannot be represented. A NaN converts to the float8 NaN.

Returns

The nearest float8.

Throws

RuntimeException
when this is infinite or finite but too large for float8 (the largest finite value is 448).

Examples

use io::console;

float8 a = 1.5.toFloat8();
console.writeln(a.toFloat());
try {
    console.writeln(1000.0.toFloat8());
} catch (RuntimeException e) {
    console.writeln("caught: ${e.message}");
}
1.5e0
caught: toFloat8: value out of range (max finite 448)

See also: float8, toFloat16, toFloat32

toInt

toInt() -> int

Convert to an int by dropping the fractional part (rounding toward zero).

Throws instead of returning a wrong number when there is no int to return.

Returns

The truncated value as an int.

Throws

RuntimeException
when this is NaN, infinite, or outside the range of a 64-bit int.

Examples

use io::console;

console.writeln(3.99.toInt());
console.writeln((0.0 - 3.99).toInt());
console.writeln(2.5.round().toInt());
try {
    console.writeln(float::NaN.toInt());
} catch (RuntimeException e) {
    console.writeln("caught: ${e.message}");
}
3
-3
3
caught: float is not finite or out of int64 range for toInt()

See also: trunc, round

toString

@Pure
toString() -> string

Format the number as text: the shortest decimal digits that read back as exactly this value, in scientific notation.

The form is one digit, a point, at least one more digit, e and the exponent, with - when the exponent is negative and no + or padding: 1.5e0, 3.0000000000000004e-1, 1.0e300. Zero is 0.0e0 and negative zero -0.0e0; the infinities are Infinity and -Infinity, and every NaN is NaN. The text is at most 24 characters, the same on every engine and platform, and string.toFloat() reads it back to the identical value. It is also what string concatenation and ${} interpolation produce.

Returns

The decimal text of this.

Examples

use io::console;

console.writeln(3.5.toString());
console.writeln(0.1 + 0.2);
console.writeln(float::NaN.toString());
console.writeln((0.0 - 1.0).sqrt().toString());
string s = "value=" + 2.0.toString();
console.writeln(s);
3.5e0
3.0000000000000004e-1
NaN
NaN
value=2.0e0

trunc

trunc() -> float

Drop the fractional part, rounding toward zero.

Unlike floor, a negative number is not rounded down: -3.99 becomes -3.0. The result is still a float; use toInt for an int.

Returns

this without its fractional part.

Examples

use io::console;

console.writeln(3.99.trunc());
console.writeln((0.0 - 3.99).trunc());
console.writeln((0.0 - 3.99).floor());
3.0e0
-3.0e0
-4.0e0

See also: floor, ceil, round, toInt

See also

  • int — The signed 64-bit integer type, the default type of whole numbers.
  • Sized floats: float8, float16, float32 — The narrow floating-point formats, how every operation re-rounds, and where they overflow or throw.
  • Numeric conversions and working types — Values cross between integer and float types only through a conversion call, lossless widening is implicit, and literals take the type their context asks for.