Last active
March 20, 2021 13:31
-
-
Save timcsy/068f017b81839884fc76f12b6bb33f06 to your computer and use it in GitHub Desktop.
牛頓法範例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} | |
double f_diff(double x, double h=1e-6) { | |
return (f(x+h)-f(x)) / h; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment