We want to solve the following equation with Newton's method: \(f(x)=xe^x-1=0\).

The method consists of defining a sequence \(\{x_n\}_{n\in\mathbb{N}}\) by: \(\begin{array}{lll} x_0=1 & & \\ x_{n+1}=x_n - \frac{f(x_n)}{f'(x_n)} & for & n \in \mathbb{N}\end{array}\)

Write a program that calculates the terms of this sequence, stops as soon as \(|f(x_n)| <10^{-10}\), and displays the result.


Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<math.h>
#include<conio.h>
void main() {

	double x=1,f,fp;
	do {
		f=x*exp(x)-1;
		fp=(1+x)*exp(x);
		x=x-f/fp;
	} while(fabs(f)>1e-10);
	printf("Solution x = %lf\n",x);

	getch();
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
DFS traversal of a graph using an adjacency matrix