Rust floating point
Created By: chatGPT
Rust provides built-in support for floating-point numbers through two primary types: f32 and f64. The f32 type represents a 32-bit floating point number, whereas f64 represents a 64-bit floating point number. The most common scenarios for using floating-point data in Rust involve calculations where decimal precision is important, such as in scientific computations or graphical applications.
let pi: f64 = 3.141592653589793;
let radius: f32 = 5.0;
let area: f32 = pi as f32 * radius * radius;
println!("Area of the circle: {}", area);
Floating-point arithmetic is subject to rounding errors due to the way numbers are stored in binary. This can lead to unexpected results during calculations. For precision-critical use cases like monetary calculations, it is often advisable to use integer types or fixed-point libraries.
let a: f64 = 0.1 + 0.2;
let b: f64 = 0.3;
assert!((a - b).abs() < std::f64::EPSILON, "Floating point numbers are not equal!");
When performing operations with floating-point numbers, it’s essential to note how Rust handles operations such as addition, subtraction, and multiplication. For instance, when dividing by zero or attempting invalid operations, Rust will provide results like NaN (Not a Number) or Infinity.
let x: f64 = 0.0;
let y: f64 = 1.0 / x;
println!("Result: {}", y); // This will result in 'Infinity'
To work with floating points effectively, Rust also provides the std::f32 and std::f64 modules, which contain useful constants and functions. These include mathematical functions like sin, cos, and exp that operate on floating-point numbers.
let angle: f64 = 30_f64.to_radians();
let sine: f64 = angle.sin();
println!("Sine of 30 degrees: {}", sine);