二分法とNewton-Raphson法

プログラミングの授業でこんなことしてます( ´ー`)y-~~おいすー

f(x)=x^2 - 4(sin2x)^2 = 0

上式を二分法とNewton-Raphson法により解くプログラムをそれぞれ作成し解を求めよ。

二分法

#include
#include
#define f(x) (x*x-4*sin(2*x)*sin(2*x))
int main(void){
int i=0,n;
double s,x,dx,x1,zx,eps=1e-10;
printf("enter x dx\n");
scanf("%lf %lf",&x,&dx);
printf("enter n\n");
scanf("%d",&n);
for(i=1;i<=n;i++){
do{
zx=x;
x=x+dx;
}while(f(x)*f(zx)>0);
do{
x1=x-f(x)/(f(x)-f(zx))*(x-zx);
zx=x;
x=x1;
}while(fabs(f(x))>eps);
printf("i=%d x=%lf f(x)=%lf\n",i,x,f(x));
x=x+dx;
}
return(0);
}

Newton-Raphson法

#include
#include
double f(double x)
{
double y;
y=x*x-4*sin(2*x)*sin(2*x);
return y;
}
double g(double x)
{
double y;
y=2*x-16*sin(2*x)*cos(2*x);
return y;
}
main(void)
{
int i;
double x0,R0,p,x1,z;
FILE *lwa;
lwa=fopen("examplenewton.txt","w");

if(lwa==NULL){
printf("Cannot open\n");
return 1;
}
printf("Input the first numeber x0=");
scanf("%lf",&x0);
for(i=1;i<10000;i++)
{
R0=0-f(x0);
p=R0/g(x0);
z=fabs(p);
printf("p=%12.11lf repeat=%d\n",p,i);
fprintf(lwa,"%d,%12.11lf \n",i,z);
if(z>1.0E-9)
{
x1=x0+p;
x0=x1;
}
else
{
break;
}
}
printf("answer=%11.10lf\n",x1);
printf("y=%20.19lf\n",f(x1));
fclose(lwa);
return 0;
}

⊂( ・∀・)ワケ ( ・∀・)つワカ ⊂( ・∀・)つラン♪