62,614
社区成员
发帖
与我相关
我的任务
分享
public static double[] getF(double[][] p)
{
//二维数组的高,为0时为非法数据,
int h=p.length;
if(h==0) return null;
//二维数组的宽,不等于h+1时为非法数据,
int w=p[0].length;
if(w!=h+1) return null;
//中间变量,用于交换;
double[] temp=new double[w];
//结果
double[] result=new double[h];
//三层循环,下三角矩阵生成,
//分别用p[0][0],p[1][1],p[2][2]...化第0,1,2列的值为0
for(int k=0;k<h;k++)
{
for(int i=k+1;i<h;i++)
{
if(p[k][k]==0)
{
temp=p[i];
p[i]=p[k];
p[k]=temp;
}
if(p[i][k]==0)continue;
double a=p[k][k]/p[i][k];
for(int j=0;j<w;j++)
{
p[i][j]=-p[i][j]*a+p[k][j];
}
}
}
//对角矩阵生成
//分别用p[h-1][h-1],p[h-2][h-2],化第h-1,h-2列的值为0
for(int k=h;k>0;k--)
{
for(int i=k-1;i>0;i--)
{
if(p[i-1][k-1]==0 ||p[k-1][k-1]==0)continue;
double a=p[k-1][k-1]/p[i-1][k-1];
for(int j=w-1;j>=0;j--)
{
p[i-1][j]=-p[i-1][j]*a+p[k-1][j];
}
}
}
//判断是否有唯一解,没有则返回null
for(int i=0;i<h;i++)
{
if(zeroNum(p[i])!=1)
return null;
}
for(int i=0;i<h;i++)
{
result[i]=(p[i][w-1]/p[i][i]);
}
return result;
}
public static int zeroNum(double[] p)
{
int notZero=0;
for(int i=0;i<p.length-1;i++)
{
if(p[i]==0)
continue;
notZero++;
}
return notZero;
}
public static void main(String args[])
{
/**
* x1+x2+x3+x4=10
* x1+x2+x3-x4=2
* x1+x2-x3+x4=4
* x1-x2+x3+x4=6
* 的对应数组
*/
double[][] p = {
{1,1,1,1,10},
{1,1,1,-1,2},
{1,1,-1,1,4},
{1,-1,1,1,6}
};
double[] a=getF(p);
System.out.println(Arrays.toString(a));
}
#include<stdio.h>
#include<math.h>
float f(float x){
float y;
y = ((x - 8.0) * x + 12.0) * x - 30;
return y;
}
double xpoint(double x1, double x2){
double r, y1 = f(x1), y2 = f(x2);
r = (x1 * y2 - x2 * y1) / (y2 - y1);
return r;
}
double root(double x1, double x2){
double x, y, y1;
y1 = f(x1);
do{
x = xpoint(x1, x2);
y = f(x);
if(y*y1 > 0){
y1 = y;
x1 = x;
}else{
x2 = x;
}
}while(abs(y) >= 0.0001);
return x;
}
int main(void){
float x1, x2, f1, f2, x;
do{
printf("Please input x1, x2: \n");
scanf("%f, %f", &x1, &x2);
f1 = f(x1);
f2 = f(x2);
printf("f1=%f, f2=%f\n", f1, f2);
}while(f1 * f2 > 0 );
x = root(x1, x2);
printf("A root of equation is %9.6f\n", x);
}