Skip to content

Commit 4e86aeb

Browse files
committed
finish nbody
1 parent 5557907 commit 4e86aeb

File tree

1 file changed

+18
-21
lines changed

1 file changed

+18
-21
lines changed

crates/core_simd/examples/nbody.rs

Lines changed: 18 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
/// Benchmarks game nbody code
2+
/// Taken from the `packed_simd` crate
3+
/// Run this benchmark with `cargo test --example body`
14
use core_simd::*;
25

36
use std::f64::consts::PI;
@@ -126,11 +129,14 @@ pub fn advance(bodies: &mut [Body; N_BODIES], dt: f64) {
126129
let mut mag = [0.0; N];
127130
let mut i = 0;
128131
while i < N {
129-
let d2s = f64x2::from_array([(r[i] * r[i]).horizontal_sum(), (r[i + 1] * r[i + 1]).horizontal_sum()]);
132+
let d2s = f64x2::from_array([
133+
(r[i] * r[i]).horizontal_sum(),
134+
(r[i + 1] * r[i + 1]).horizontal_sum(),
135+
]);
130136
let dmags = f64x2::splat(dt) / (d2s * d2s.sqrt());
131137
// dmags.write_to_slice_unaligned(&mut mag[i..]);
132138
mag[i] = dmags[0];
133-
mag[i+1] = dmags[1];
139+
mag[i + 1] = dmags[1];
134140
i += 2;
135141
}
136142

@@ -166,28 +172,19 @@ pub fn run(n: usize) -> (f64, f64) {
166172
(energy_before, energy_after)
167173
}
168174

169-
const OUTPUT: [f64; 2] = [-0.169075164, -0.169087605];
175+
fn approx_eq_f32(a: f32, b: f32) -> bool {
176+
(a - b).abs() < 0.00000001
177+
}
178+
170179
#[cfg(test)]
171180
mod tests {
172181
#[test]
173182
fn test() {
174-
let mut out: Vec<u8> = Vec::new();
175-
run(&mut out, 1000, 0);
176-
for &(size, a_e, b_e) in crate::RESULTS {
177-
let (a, b) = super::run(size);
178-
assert_eq!(format!("{:.9}", a), a_e);
179-
assert_eq!(format!("{:.9}", b), b_e);
180-
}
183+
use super::*;
184+
const OUTPUT: [f64; 2] = [-0.169075164, -0.169087605];
185+
let (energy_before, energy_after) = super::run(1000);
186+
assert!(approx_eq_f32(energy_before as f32, OUTPUT[0] as f32));
187+
assert!(approx_eq_f32(energy_after as f32, OUTPUT[1] as f32));
188+
// }
181189
}
182190
}
183-
184-
185-
fn main() {
186-
//let n: usize = std::env::args()
187-
//.nth(1)
188-
//.expect("need one arg")
189-
//.parse()
190-
//.expect("argument should be a usize");
191-
//run(&mut std::io::stdout(), n, alg);
192-
println!("{:?}", run(10));
193-
}

0 commit comments

Comments
 (0)