The
Floating-Point Types
are available in 32-bit (f32) and 64-bit (f64) versions.
Table 1 presents the available floating-point operators.
Table 1:Floating-point operators
Operator | Description |
|---|---|
| Addition |
| Subtraction |
| Multiplication |
| Division |
| Remainder |
6.2.1Default type¶
The default type for floats is f64:
let x = 10.0; // Default type: f64
x10.06.2.2Specifying the type¶
As for integers, the type can be set either to the variable or the value:
let x: f32 = 3.0;
let y = 3.0f32;
(x, y)(3.0, 3.0)6.2.3Operations¶
Example of computing a remainder:
34.56 % 3.62.1600000000000015A division:
34.56 / 3.69.66.2.4Type related constants¶
Many useful constants are directly accessible on the primitive type f64 or f32.
For 32-bit float numbers:
println!("Number of significant digits: {}", f32::DIGITS);
println!("Maximum: {:.2e}", f32::MAX);
println!("Minimum: {:.2e}", f32::MIN);
println!("NaN: {}", f32::NAN);
println!("Infinity: {}", f32::INFINITY);
println!("Negative infinity: {}", f32::NEG_INFINITY);
println!("ε: {:.2e}", f32::EPSILON);Number of significant digits: 6
Maximum: 3.40e38
Minimum: -3.40e38
NaN: NaN
Infinity: inf
Negative infinity: -inf
ε: 1.19e-7
For 64-bit float numbers:
println!("Number of significant digits: {}", f64::DIGITS);
println!("Maximum: {:.2e}", f64::MAX);
println!("Minimum: {:.2e}", f64::MIN);
println!("NaN: {}", f64::NAN);
println!("Infinity: {}", f64::INFINITY);
println!("Negative infinity: {}", f64::NEG_INFINITY);
println!("ε: {:.2e}", f64::EPSILON);Number of significant digits: 15
Maximum: 1.80e308
Minimum: -1.80e308
NaN: NaN
Infinity: inf
Negative infinity: -inf
ε: 2.22e-16
6.2.5Mathematical constants¶
Multiple useful mathematical float constants can be found in std::f32::consts and std::f64::consts.
Here are some examples of constants for the 32-bit float type:
println!("e={}", std::f32::consts::E);
println!("π={}", std::f32::consts::PI);
println!("1/π={}", std::f32::consts::FRAC_1_PI);
println!("φ={}", std::f32::consts::GOLDEN_RATIO);e=2.7182817
π=3.1415927
1/π=0.31830987
φ=1.618034