2-7 正割法 Program to find root of an equations using secant method
源自於
Examples :
Input : equation = x3 + x - 1
x1 = 0, x2 = 1, E = 0.0001
Output : Root of the given equation = 0.682326
No. of iteration=5
Algorithm
Initialize: x1, x2, E, n // E = convergence indicator calculate f(x1),f(x2) if(f(x1) * f(x2) = E); //repeat the loop until the convergence print 'x0' //value of the root print 'n' //number of iteration } else print "can not found a root in the given interval"
程式:
// C Program to find root of an equations using secant method
#include <stdio.h>
// function takes value of x and returns f(x)
float f(float x)
{
// we are taking equation as x^3+x-1
float f = pow(x, 3) + x - 1;
return f;
}
void secant(float x1, float x2, float E)
{
float n = 0, xm, x0, c;
if (f(x1) * f(x2) < 0)
{
do {
// calculate the intermediate value
x0 = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1));
// check if x0 is root of equation or not
c = f(x1) * f(x0);
// update the value of interval
x1 = x2;
x2 = x0;
// update number of iteration
n++;
// if x0 is the root of equation then break the loop
if (c == 0)
break;
xm = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1));
printf("xm=%0.5lf\n", xm);
} while (fabs(xm - x0) >= E); // repeat the loop
// until the convergence
printf("Root of the given equation=%0.5lf", x0);
printf("\nNo. of iterations = %0.0lf", n);
} else
printf("Can not find a root in the given inteval");
}
// Driver code
int main()
{
// initializing the values
float x1 = 0, x2 = 1, E = 0.0001;
secant(x1, x2, E);
return 0;
}
輸出結果
xm=0.69005
xm=0.68202
xm=0.68233
xm=0.68233
Root of the given equation=0.68233
No. of iterations = 5
沒有留言:
張貼留言