Untitled

 avatar
unknown
c_cpp
3 years ago
1.2 kB
2
Indexable
#include <bits/stdc++.h>
using namespace std;
 
float f(float x) // f(x) function. 
{
	return sin(x) * sin(x) + x - 1; // insert your equation here.
}
float df(float x) // f'(x) function. 
{
	return sin(2 * x) + 1; // insert the first derivative of your equation here. 
}
void newton_raphson(float x0) // Main Algorithm of newton_raphson method. 
{
	printf("---------------------------\nRoot using Newton-Raphson Method\n---------------------------\n");
	int iteration = 1; // for counting iteration. 
 
	float x1; // x_n+1 declaration. 
 
	while (1) // infinite loop. This will run until we found the desirable result. 
	{
		x1 = x0 - (f(x0) / df(x0)); // Main formula of newton raphson method.  ( x_n+1 = x_n - (f(x_n)/ f'(x_n)));
 
		printf(" Iteration = %d\tx0 = %.5f\tx1 = %.5f\tf(x1) = %.5f\n", iteration, x0, x1, f(x1)); // printing results.
 
		if (abs(f(x1)) == 0) 
		{
			break; // if we found the root loop will be terminated. 
		}
		else
		{
			x0 = x1;
		}
		iteration++;
	}
	cout << "The smallest root: " << x1 << '\n';
}
 
 
 
 
 
int main()
{
	float x0, x1;
	cout << "Enter your initial guess: ";
	cin >> x0;
	newton_raphson(x0);
}
Editor is loading...