Skip to content

Instantly share code, notes, and snippets.

@timcsy
Last active March 20, 2021 13:31
Show Gist options
  • Save timcsy/068f017b81839884fc76f12b6bb33f06 to your computer and use it in GitHub Desktop.
Save timcsy/068f017b81839884fc76f12b6bb33f06 to your computer and use it in GitHub Desktop.
牛頓法範例
// 比較可以重複利用牛頓法的寫法(使用 function pointer)
#include <iostream>
using namespace std;
typedef double (*Equation)(double x); // 把 function pointer 命名為 Equation
double diff(Equation f, double x, double h=1e-6) {
return (f(x + h) - f(x)) / h;
}
// The format should be the left part of the equation f(x) = 0
double f1(double x) {
// You can change the function by yourself
return x * x - 2;
}
// Another example of the equation
double f2(double x) {
// to solve the equation x^2 -5x + 6 = 0, you will get different answer for different initial values
// You will get x = 2 if the initial value is for example, 0
// You will get x = 3 if the initial value is for example, 5
// You can try different initial values!
return x*x - 5*x + 6;
}
// Another example of the equation
double f3(double x) {
// to solve the equation x^3 - 6x^2 + 11x - 6 = 0
return x*x*x - 6*x*x + 11*x - 6;
}
double newton(Equation f, double x_init, int N) {
double x = x_init;
for (int i = 0; i < N; i++) {
x = x - (f(x) / diff(f, x));
}
return x;
}
int main() {
double x;
int N;
cout << "Please enter a initial point: ";
cin >> x;
cout << "Please enter the times to apply the Newton method (such as 100): ";
cin >> N;
cout << "We have the root: " << newton(f3, x, N) << endl;
return 0;
}
// 用牛頓法計算根號2的範例
#include <iostream>
using namespace std;
double f(double x) {
return x * x - 2; // f(x) = x^2 - 2 = 0, to find x^2=2, x = ?
}
double f_diff(double x, double h=1e-6) {
return (f(x + h) - f(x)) / h;
}
double newton(double x_init, int N) {
double x = x_init;
for (int i = 0; i < N; i++) {
double x_next = x - (f(x) / f_diff(x));
x = x_next;
}
return x;
}
int main() {
double x;
int N;
cout << "Please enter a initial point: ";
cin >> x;
cout << "Please enter the times to apply the Newton method: ";
cin >> N;
cout << "We have the root: " << newton(x, N) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment