Skip to content

Add rust implementation of forward euler #182

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 3, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CONTRIBUTORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ Pen Pal
Chinmaya Mahesh
Unlambder
Kjetil Johannessen
CDsigma
CDsigma
hsjoihs
33 changes: 33 additions & 0 deletions chapters/differential_equations/euler/code/rust/euler.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
fn main() {
let mut result = [0.0;100];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should consider formatting your code with rustfmt so it conforms to the standard styleguide.

let threshold = 0.01;
let timestep = 0.01;

solve_euler(timestep, &mut result, 100);
println!("{}", check_result(&result, 100, threshold, timestep));
}


fn solve_euler(timestep: f64, result: &mut [f64], n: usize) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't need to pass n, Rust slices already know their size. Also, I would pass a &[f64] and return an Option<Vec<f64>> which would be much more idiomatic.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops! Thanks

if n != 0 {
result[0] = 1.0;
for i in 1..n {
result[i] = result[i-1] - 3.0 * result[i-1] * timestep;
}
}
}


fn check_result(result: &[f64], n: usize, threshold: f64, timestep: f64) -> bool {
let mut is_approx: bool = true;
for i in 0..n {
let solution = (-3.0 * i as f64 * timestep).exp();
if (result[i] - solution).abs() > threshold {
println!("{} {}", result[i], solution);
is_approx = false;
}
}

return is_approx;
}

3 changes: 3 additions & 0 deletions chapters/differential_equations/euler/euler.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ So, this time, let's remove ourselves from any physics and instead solve the fol
{% sample lang="cpp" %}
### C++
[import, lang:"c_cpp"](code/c++/euler.cpp)
{% sample lang="rs" %}
### Rust
[import, lang:"rust"](code/rust/euler.rs)
{% sample lang="elm" %}
### Elm
[import:44-54, lang:"elm"](code/elm/euler.elm)
Expand Down