Skip to content

Instantly share code, notes, and snippets.

@shanecelis
Last active August 22, 2018 05:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shanecelis/976f901fab5eebd3d68b479181999f01 to your computer and use it in GitHub Desktop.
Save shanecelis/976f901fab5eebd3d68b479181999f01 to your computer and use it in GitHub Desktop.
/* Original code Copyright (c) 2018 Shane Celis[1]
Licensed under the MIT License[2]
Original code posted here[3].
This comment generated by code-cite[4].
[1]: https://github.com/shanecelis
[2]: https://opensource.org/licenses/MIT
[3]: https://gist.github.com/shanecelis/976f901fab5eebd3d68b479181999f01
[4]: https://github.com/shanecelis/code-cite
*/
using System;
/*
Burden, R. L., & Faires, J. D. (2005). Numerical analysis (8 ed.). Belmont, CA: Thomson Brooks/Cole.
*/
public static class NumericalMethods {
/*
This is known as the forward-difference formula if h > 0 and the
backward-difference formula if h < 0 (Burden 168).
*/
public static Func<float, float> Derivative(Func<float, float> f, float h) {
return x => (f(x + h) - f(x)) / h;
}
/* Given a guess p_n, this will return p_{n + 1}. (Burden 64) */
public static Func<float, float> NewtonsMethodStep(Func<float, float> f, Func<float, float> df) {
// Returns p_{n + 1}
return p_n => p_n - f(p_n) / df(p_n);
}
/* Find a root of an equation: Find the p where f(p) = 0. (Burden 65) */
public static float NewtonsMethod(Func<float, float> f, Func<float, float> df, float p_0, float tolerance, int maxSteps) {
var step = NewtonsMethodStep(f, df);
int i = 0;
float p = p_0;
do {
p_0 = p;
p = step(p_0);
} while (Math.Abs(p - p_0) > tolerance && i++ < maxSteps);
return p;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment