-
Notifications
You must be signed in to change notification settings - Fork 1
/
1a-newtonraphson.cpp
56 lines (41 loc) · 1.35 KB
/
1a-newtonraphson.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include<iostream>
#include<iomanip> /* setprecision & setw */
#include<math.h> /* fabs */
// Fungsi f(x): x^3 + 2x^2 + 10 x = 20
#define f(x) pow(x, 3) + pow(2*x, 2) + 10*x - 20
// Turunan fungsi f(x) sebagai g(x): 3x^2 + 4x + 10
#define g(x) pow(3*x, 2) + 4*x + 10
using namespace std;
int main(){
float x0, x1, f0, f1, g0, e;
int iterasi = 1, N;
// 6 digit dibelakang koma
cout << setprecision(6) << fixed;
cout << "=======================================" << endl;
cout << "======== Metode Newton-Raphson ========" << endl;
cout << "=======================================" << endl;
// Input
cout << "Masukkan nilai x0: "; cin >> x0;
cout << "Masukkan toleransi error: "; cin >> e;
cout << "Masukkan maksimum iterasi: "; cin >> N;
do {
g0 = g(x0);
if (g0 == 0.0) {
cout << "Error";
exit(0);
}
f0 = f(x0);
// Metode Newton Raphson Xn+1 = Xn - {f(Xn)/f'(Xn)}
x1 = x0 - f0/g0;
cout << "Iterasi ke-" << iterasi <<":\tx =" << setw(10);
cout << x1 << " dan f(x) =" << setw(10) << f(x1) << endl;
x0 = x1;
iterasi++;
if (iterasi > N){
cout << "Tidak konvergen (tidak mendekati titik temu).";
exit(0);
}
f1 = f(x1);
} while (fabs(f1)>e);
return 0;
}