Skip to content

Commit 2a8bf4d

Browse files
hsjoihszsparal
authored andcommitted
Add rust implementation of forward euler (#182)
* Add rust implementation of forward euler * remove n's from the arguments, as they are obviously unnecessary * rustfmt
1 parent bc7d50e commit 2a8bf4d

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed

CONTRIBUTORS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,6 @@ Chinmaya Mahesh
1313
Unlambder
1414
Kjetil Johannessen
1515
CDsigma
16+
hsjoihs
1617
DominikRafacz
1718
lulucca12
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
fn main() {
2+
let mut result = [0.0; 100];
3+
let threshold = 0.01;
4+
let timestep = 0.01;
5+
6+
solve_euler(timestep, &mut result);
7+
println!("{}", check_result(&result, threshold, timestep));
8+
}
9+
10+
fn solve_euler(timestep: f64, result: &mut [f64]) {
11+
let n = result.len();
12+
if n != 0 {
13+
result[0] = 1.0;
14+
for i in 1..n {
15+
result[i] = result[i - 1] - 3.0 * result[i - 1] * timestep;
16+
}
17+
}
18+
}
19+
20+
fn check_result(result: &[f64], threshold: f64, timestep: f64) -> bool {
21+
let mut is_approx: bool = true;
22+
for (i, val) in result.iter().enumerate() {
23+
let solution = (-3.0 * i as f64 * timestep).exp();
24+
if (val - solution).abs() > threshold {
25+
println!("{} {}", val, solution);
26+
is_approx = false;
27+
}
28+
}
29+
30+
return is_approx;
31+
}

chapters/differential_equations/euler/euler.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,9 @@ So, this time, let's remove ourselves from any physics and instead solve the fol
107107
{% sample lang="cpp" %}
108108
### C++
109109
[import, lang:"c_cpp"](code/c++/euler.cpp)
110+
{% sample lang="rs" %}
111+
### Rust
112+
[import, lang:"rust"](code/rust/euler.rs)
110113
{% sample lang="elm" %}
111114
### Elm
112115
[import:44-54, lang:"elm"](code/elm/euler.elm)

0 commit comments

Comments
 (0)