📄 interpolating polynomial.c
字号:
// Write a computer program using a Lagrange interpolating polynomial of the 10th order to evaluate f(x)=lnx where [a, b]=[1,2], h=0.1, xi = 1+ih, i=0, 1, …, 10, and find the approximations of ln1.54 and ln1.98.
//
#include "stdio.h"
#include "math.h"
#define N 10
float f(float x)
{
float y;
y=log(x);
return(y);
}
void lag(float a[],float b[],int n,float x)
{
int i,j;
for(i=0;i<=n;i++)
for(j=0;j<=n;j++)
if(i!=j)
b[i]=b[i]*(x-a[j])/(a[i]-a[j]);
}
float sum(float a[],float b[],int n)
{
float y=0;
int i;
for(i=0;i<=n;i++)
y=y+f(a[i])*b[i];
return(y);
}
main()
{
float x,y;
float m[N+1];
float l[N+1];
int i;
for(i=0;i<=N;i++)
{
m[i]=1+0.1*i;
l[i]=1;
}
do
{
printf("input x belong to [1,2]:\n");
scanf("%f",&x);
}while((x<1)||(x>2));
lag(m,l,N,x);
y=sum(m,l,N);
printf("f(%f)=%8.4f\n",x,y);
getchar();
getchar();
}
// Write and test a computer program to implement the Bisection algorithm. Test program on the function and interval: 2-x+ex+2cosx-6 on [1, 3].
#include "stdio.h"
#include "math.h"
float f(float x)
{
float y;
y=pow(0.5,x)+exp(x)+2*cos(x)-6;
return(y);
}
float mid_point(float x1,float x2)
{
float y;
y=(x1+x2)/2;
return(y);
}
float root(float x1,float x2)
{
float x,y;
do
{
x=mid_point(x1,x2);
y=f(x);
if(y*f(x1)>0)
{
x1=x;
}
else
{
x2=x;
}
}while(fabs(y)>=0.001);
return(x);
}
main()
{
float x1,x2,f1,f2,x;
do
{
printf("input x1,x2:\n");
scanf("%f,%f",&x1,&x2);
f1=f(x1);
f2=f(x2);
}while(f1*f2>=0);
x=root(x1,x2);
printf("A root of equation is %8.4f\n",x);
getchar();
getchar();
}
// Write a brief computer program to solve the equation x3+3x=5x2+7 by Newton’s method. Take ten steps starting at x0=5.
#include "stdio.h"
#include "math.h"
#define N 10
float f(float x)
{
float y;
y=x*x*x-5*x*x+3*x-7;
return(y);
}
float f1(float x)
{
float y;
y=3*x*x-10*x+3;
return(y);
}
float root(float x0,int n)
{
float x;
int i;
for(x=x0,i=0;i<n;i++)
{
x=x-f(x)/f1(x);
}
return(x);
}
main()
{
float x0,x;
printf("input initial x0:\n");
scanf("%f",&x0);
x=root(x0,N);
printf("A root of equation is %8.4f\n",x);
getchar();
getchar();
}
// Write a computer program to carry out the Secant method on a function f, assuming that two starting points are given. Test the routine on the function f = x3-12x2+3x+1.
#include "stdio.h"
#include "math.h"
float f(float x)
{
float y;
y=x*x*x-12*x*x+3*x+1;
return(y);
}
float f1(float x1,float x2)
{
float y;
y=(f(x2)-f(x1))/(x2-x1);
return(y);
}
float root(float x1,float x2)
{
float x;
x=x2;
while(fabs(f(x))>=0.0001)
{
x=x-f(x)/f1(x1,x2);
x1=x2;
x2=x;
}
return(x);
}
main()
{
float x1,x2,x;
printf("input initial x1,x2:\n");
scanf("%f,%f",&x1,&x2);
x=root(x1,x2);
printf("A root of equation is %8.4f\n",x);
getchar();
getchar();
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -