Trigonometry
Calculating the side length of a triangle
Calculates the length of the hypotenuse of a right-angle triangle with an angle of 2 radians and opposite side length of 80.
fn main() { let angle: f64 = 2.0; let side_length = 80.0; let hypotenuse = side_length / angle.sin(); println!("Hypotenuse: {}", hypotenuse); }
Verifying tan is equal to sin divided by cos
Add the approx
crate to your own project:
cargo add approx
Verifies tan(x) is equal to sin(x)/cos(x) for x = 6.
While, in this particular case, the results of these computations
produce an identical result, in general you should not be using
the standard equality operator to compare to floating point numbers.
Instead, this example uses the approx
crate for floating point
comparisons.
You can experiment with this by enabling the assertion, and changing
the x
value to something else like 0.1 for example.
use approx::assert_ulps_eq; fn main() { let x: f64 = 6.0; let a = x.tan(); let b = x.sin() / x.cos(); println!("{} {}", a, b); assert_ulps_eq!(a, b); /* * Standard equality also works for x = 6.0, but may not for other values. */ // assert_eq!(a, b); }
Distance between two points on the Earth
By default, Rust provides mathematical float methods such as trigonometric functions, square root, conversion functions between radians and degrees, and so forth.
The following example computes the distance in kilometers between two
points on the Earth with the Haversine formula. Points are expressed
as pairs of latitude and longitude in degrees. Then, to_radians
converts them in radian. sin
, cos
, powi
and sqrt
compute the central angle. Finally, it's possible to calculate the
distance.
fn main() { let earth_radius_kilometer = 6371.0_f64; let (paris_latitude_degrees, paris_longitude_degrees) = (48.85341_f64, -2.34880_f64); let (london_latitude_degrees, london_longitude_degrees) = (51.50853_f64, -0.12574_f64); let paris_latitude = paris_latitude_degrees.to_radians(); let london_latitude = london_latitude_degrees.to_radians(); let delta_latitude = (paris_latitude_degrees - london_latitude_degrees).to_radians(); let delta_longitude = (paris_longitude_degrees - london_longitude_degrees).to_radians(); let central_angle_inner = (delta_latitude / 2.0).sin().powi(2) + paris_latitude.cos() * london_latitude.cos() * (delta_longitude / 2.0).sin().powi(2); let central_angle = 2.0 * central_angle_inner.sqrt().asin(); let distance = earth_radius_kilometer * central_angle; println!( "Distance between Paris and London on the surface of Earth is {:.1} kilometers", distance ); }