#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define e 2.71828182
float
fun(
float
x)
{
x=(x*x*x)-(2*x)-2;
//x=2*x-log10(x)-7;
//x=pow(x,3)-x-4;
//x=(x*(pow(e,x)))-2;
return
x;
}
float
in(
float
a,
float
b)
{
float
x; x=((a*fun(b))-(b*fun(a)))/(fun(b)-fun(a));
return
x;
}
int
main()
{
int
i,n;
float
p[20];
float
a,b,x[100];
printf
(
"\n given question is : x^3+2x-2 =0 \n"
);
printf
(
"\n Enter n : "
);
scanf
(
"%d"
,&n);
for
(i=0;i<n;i++)
{
p[i]=fun(i);
printf
(
"\n f[%d] : %0.1f "
,i,p[i]);
}
for
(i=0;i<n;i++)
{
if
(p[i]*p[i+1]<0)
{
a=i;
b=i+1;
printf
(
"\n\n your interval found between : [%2.4f %2.4f]"
,a,b);
break
;
}
}
for
(i=0;i<n;i++)
{
x[i]=in(a,b);
printf
(
"\n x[%d] : %f "
,i,x[i]);
if
(fun(x[i])*fun(a) > 0)
{
a=x[i];
}
else
{
b=x[i];
}
}
return
0;
}
-----------------------------------------------------------------------------
another method
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
float f(float x) {
float fx;
fx = x*pow(2.714,x) -2;
//x=2*x-log10(x)-7;
//x=pow(x,3)-x-4;
//x=(x*(pow(e,x)))-2;
}
float rootB(float a, float b) {
float c;
c = (((a*f(b))-(b*f(a))))/(f(b)-f(a));
if(f(c)==0){
printf("%f ",f(c));
return c;
}
else if(f(c)<0) {
return rootB(c,b);
}
else{
return rootB(a,c);
}
}
int main()
{
float a,b,ans;
float i;
for(i=-5;i<=5;i++) {
if(f(i)*f(i+1)<0) {
if(f(i)<0){
ans = rootB(i,i+1);
}
else {
ans = rootB(i+1,i);
}
printf("ans is %f",ans);
}
}
return 0;
}
By - Sahil Patki
No comments:
Post a Comment