ASSIGNMENT – 2
Problem Statement: Write a C program to find a root of the equation f(x) = x3 – x2 + 2 = 0
using Newton-Raphson method, correct up to 4 significant figures.
Solution:
Algorithm:
➢ Start
➢ Define ( f(x) = x^3 - x^2 + 2 ) and its derivative ( f'(x) = 3x^2 - 2x ).
➢ Declare variables for the current approximation (`x0`), next approximation (‘x1’),
tolerance (‘0.0001’), maximum iterations (‘100’), and iteration counter.
➢ Prompt the user for an initial guess and store it in ‘x0’.
➢ Start a ‘do-while’ loop that continues until the absolute value of ( f(x1) ) is less than the
tolerance or the maximum iterations are reached.
➢ Compute ( f(x0) ) and ( f'(x0) ).
➢ If the derivative is too small, print a message and exit.
➢ Calculate the next approximation using ( x1 = x0 - frac{f(x0)}{f'(x0)} ).
➢ Display the current iteration number, ( x1 ), and ( f(x1) ).
➢ Update ‘x0’ to ‘x1’ and increment the iteration counter.
➢ After exiting the loop, print the found root formatted to four significant figures.
➢ Return 0 to indicate successful completion
➢ Stop
Program
Code:
#include <stdio.h>
#include <math.h>
double f(double x) {
return x * x * x - x * x + 2;
}
double f_derivative(double x) {
return 3 * x * x - 2 * x;
}
int main() {
double x0, x1;
double tolerance = 0.0001;
int max_iterations = 100;
int iteration = 0;
printf("Enter initial guess: ");
scanf("%lf", &x0);
do {
double f_x0 = f(x0);
double f_prime_x0 = f_derivative(x0);
if (fabs(f_prime_x0) < 1e-10) {
printf("Derivative is too small. No solution found.\n");
return 1;
}
x1 = x0 - f_x0 / f_prime_x0;
printf("Iteration %d: x = %.6lf, f(x) = %.6lf\n", iteration + 1, x1, f(x1));
x0 = x1;
iteration++;
} while (fabs(f(x1)) > tolerance && iteration < max_iterations);
printf("Root found: %.4lf\n", x1);
return 0;
}
Output:
Discussion: The Newton-Raphson method to find a root of the equation $ f(x) = x^3 - x^2 +
2 $. It defines two functions: one for the equation and another for its derivative. The program
prompts the user for an initial guess and iteratively applies the Newton-Raphson formula to
refine the approximation of the root. It checks for convergence based on a specified tolerance
and ensures the derivative is not too small to avoid division by zero. The results, including the
current approximation and function value, are printed at each iteration, and the final root is
displayed formatted to four significant figures.