Assignment 5: Regula-Falsi
#include <stdio.h>
#include <conio.h>
#include <math.h>
#define EPSILON 0.0001 // Desired accuracy
// Function for which we are finding the root
float f(float x)
{
return x * x * x - x - 1; // Example: f(x) = x^3 - x - 1
}
void main()
{
float a, b, c;
int i = 0;
clrscr();
printf("Enter two initial guesses (a and b):\n");
scanf("%f %f", &a, &b);
if (f(a) * f(b) >= 0)
{
printf("Incorrect initial guesses. f(a) and f(b) must have opposite signs.\n");
getch();
return;
}
printf("\nIter\t a\t\t b\t\t c\t\t f(c)\n");
do
{
c = (a * f(b) - b * f(a)) / (f(b) - f(a)); // Regula Falsi formula
printf("%d\t %f\t %f\t %f\t %f\n", ++i, a, b, c, f(c));
if (f(a) * f(c) < 0)
b = c;
else
a = c;
} while (fabs(f(c)) > EPSILON);
printf("\nThe root is: %f\n", c);
getch();
}
Output:
Enter two initial guesses (a and b):
1 2
Iter a b c f(c)
1 1.000000 2.000000 1.333333 -0.962963
2 1.333333 2.000000 1.462687 -0.333338
3 1.462687 2.000000 1.504019 -0.106995
4 1.504019 2.000000 1.518986 -0.034069
5 1.518986 2.000000 1.523720 -0.010730
6 1.523720 2.000000 1.525240 -0.003374
7 1.525240 2.000000 1.525731 -0.001058
8 1.525731 2.000000 1.525882 -0.000331
9 1.525882 2.000000 1.525929 -0.000104
10 1.525929 2.000000 1.525944 -0.000033
The root is: 1.525944