三角法
三角形の辺の長さを計算する
角度が1ラジアンで、対辺の長さが80の直角三角形の斜辺の長さを計算します。
fn main() {
let angle: f64 = 1.0;
let side_length = 80.0;
let hypotenuse = side_length / angle.sin();
println!("Hypotenuse: {}", hypotenuse);
}
tan が sin を cos で割った値に等しいことの検証
x = 6 のとき、tan(x) が sin(x)/cos(x) に等しいことを検証します。
fn main() {
let x: f64 = 6.0;
let a = x.tan();
let b = x.sin() / x.cos();
assert_eq!(a, b);
}
地球上の2点間の距離
デフォルトでは、Rust は三角関数、平方根、ラジアンと度の間の変換関数 などの数学的な float methods を提供しています。
次の例では、Haversine formula を使って、地球上の2点間の距離を
キロメートル単位で計算します。点は、度単位の緯度と経度の組として
表されます。次に、to_radians でそれらをラジアンに変換します。
sin、cos、powi、sqrt で中心角を計算し、
最後に、距離を計算できます。
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
);
}