Haversine formula: Difference between revisions

→‎{{header|Rust}}: Improved Rust implementation which doesn't rely on mutable function arguments
(→‎{{header|Vlang}}: Rename "Vlang" in "V (Vlang)")
(→‎{{header|Rust}}: Improved Rust implementation which doesn't rely on mutable function arguments)
Line 3,001:
=={{header|Rust}}==
<syntaxhighlight lang="rust">
use std::f64;
 
static R: f64 = 6372.8;
 
struct Point {
lat: f64,
Line 3,010 ⟶ 3,006:
}
 
fn haversine(mut origin: Point, mut destination: Point) -> f64 {
origin.lonconst R: f64 -= destination6372.lon8;
origin.lon = origin.lon.to_radians();
origin.lat = origin.lat.to_radians();
destination.lat = destination.lat.to_radians();
let dz: f64 = origin.lat.sin() - destination.lat.sin();
let dx: f64 = origin.lon.cos() * origin.lat.cos() - destination.lat.cos();
let dy: f64 = origin.lon.sin() * origin.lat.cos();
((dx * dx + dy * dy + dz * dz).sqrt() / 2.0).asin() * 2.0 * R
 
origin.lonlet lat1 = origin.lonlat.to_radians();
fn main() {
let origin: Pointlat2 = Point {destination.lat.to_radians();
let d_lat = lat2 lat:- 36.12,lat1;
origin.latlet d_lon = (destination.lon - origin.latlon).to_radians();
lon:-86.67
 
};
let a = (d_lat / 2.0).sin().powi(2) + (d_lon / 2.0).sin().powi(2) * lat1.cos() * lat2.cos();
let destination: Point = Point {
let c = 2.0 lat:* 33a.sqrt().94,asin();
R * lon:-118.4c
};
let d: f64 = haversine(origin, destination);
println!("Distance: {} km ({} mi)", d, d / 1.609344);
}
 
#[cfg(test)]
mod test {
use super::{Point, haversine};
 
#[test]
fn test_haversine() {
let origin: Point = Point {
lat: 36.12,
lon: -86.67
};
let destination: Point = Point {
lat: 33.94,
lon: -118.4
};
let dzd: f64 = origin.lat.sinhaversine() -origin, destination.lat.sin();
println!("Distance: {} km ({} mi)", d, d / 1.609344);
assert_eq!(d, 2887.2599506071106);
};
 
</syntaxhighlight>Output <pre>Distance: 2887.2599506071106 km (1794.060157807846 mi)</pre>
 
2

edits