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.
牛頓法範例
#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