## 初学程序，拟牛顿法怎样c转java代码。写不对呢。拜托各位大神帮助帮助小妹~。~

package algorithm;

public class Quasi_Newton {

G_gauss g;

public Quasi_Newton(String string){
g=new G_gauss();
}

public int fhntn(int n,double eps,double t,double h,double x[],int k){

int i,j,l;
double am,z,beta,d;
double[] y=new double[n];
double a[],b[];

//迭代求解
l=k;
am=1.0+eps;
while(am>=eps)
{
fhntnf(x,b,n);
am=0.0;
for(i=0;i<=n-1;i++)
{
z=Math.abs(b[i]);
if(z>am)
am=z;
}
if(am>=eps)
{
l=l-1;
if(l==0)
{
System.out.println("fail");
return(0);
}
for(j=0;j<=n-1;j++)
{
z=x[j];
x[j]=x[j]+h;

fhntnf(x,y,n);

for(i=0;i<=n-1;i++)
{
a[i*n+j]=y[i];
x[j]=z;
}
}

//调用全选主元高斯消元法
if(g.cagaus(a,b,n,y)==0)
{
return(-1);
}
beta=1.0;
for(i=0;i<=n-1;i++)
{
beta=beta-y[i];
}
if(Math.abs(beta)+1.0==1.0)
{
System.out.println("fail");
return(-2);
}
d=h/beta;
for(i=0;i<=n-1;i++)
{
x[i]=x[i]-d*y[i];
h=t*h;
}
}
}
//是否在有效迭代次数内达到精度
return(k-l);
}

public static void main(String[] agrs){
Quasi_Newton qn=new Quasi_Newton(null);
//求解
int i,k=100;
double[] x={1.0,1.0,1.0};
double t=0.1;
double h=0.1;
double eps=0.0000001;

i=qn.fhntn(3,eps,t,h,x,k);
System.out.println("i="+i);

for(i=0;i<=2;i++)
{
System.out.println("x("+i+")="+x[i]);
}
}
public double fhntnf(double x[],double y[],int n){
y[0]=x[0]*x[0]+x[1]*x[1]+x[2]*x[2]-1.0;
y[1]=2.0*x[0]*x[0]+x[1]*x[1]-4.0*x[2];
y[2]=3.0*x[0]*x[0]-4.0*x[1]+x[2]*x[2];
return 0;
}

}

G_gauss的代码。

package algorithm;

public class G_gauss{

public int cagaus(double a[],double b[],int n,double x[]){

int l,k,i,j,is=0,p,q;
double d,t;
int[] js=new int[n];

//消元
l=1;
for(k=0;k<=n-2;k++)
{
d=0.0;
for(i=k;i<=n-1;i++)
{
for(j=k;j<=n-1;j++)
{
t=Math.abs(a[i*n+j]);
if(t>d)
{
d=t;
js[k]=j;
is=i;
}
}
}
if(d+1.0==1.0)
l=0;
else
{
if(js[k]!=k)
{
for(i=0;i<=n-1;i++)
{
p=i*n+k;
q=i*n+js[k];
t=a[p];
a[p]=a[q];
a[q]=t;
}
}

if(is!=k)
{
for(j=k;j<=n-1;j++)
{
p=k*n+j;
q=is*n+j;
t=a[p];
a[p]=a[q];
a[q]=t;
}
t=b[k];
b[k]=b[is];
b[is]=t;
}
}
//求解失败
if(l==0)
{
System.out.println("fail");
return(0);
}
d=a[k*n+k];
for(j=k+1;j<=n-1;j++)
{
p=k*n+j;
a[p]=a[p]/d;
}
b[k]=b[k]/d;
for(i=k+1;i<=n-1;i++)
{
for(j=k+1;j<=n-1;j++)
{
p=i*n+j;
a[p]=a[p]-a[i*n+k]*a[k*n+j];
}
b[i]=b[i]-a[i*n+k]*b[k];
}
}
//求解失败
d=a[(n-1)*n+n-1];
if(Math.abs(d)+1.0==1.0)
{
System.out.println("fail");
return(0);
}
//求解
x[n-1]=b[n-1]/d;
for(i=n-2;i>=0;i--)
{
t=0.0;
for(j=i+1;j<=n-1;j++)
t=t+a[i*n+j]*x[j];
x[i]=b[i]-t;
}
//调整解的位置
js[n-1]=n-1;
for(k=n-1;k>=0;k--)
{
if(js[k]!=k)
{
t=x[k];
x[k]=x[js[k]];
x[js[k]]=t;
}
}
return(1);
}

public static void main(String[] args){
G_gauss g=new G_gauss();

int i;
//系数矩阵数据
double[] a={0.2368,0.2471,0.2568,1.2671,
0.1968,0.2071,1.2168,0.2271,
0.1581,1.1675,0.1768,0.1871,
1.1161,0.1254,0.1397,0.1490};
//常熟矩阵数据
double[] b={1.8471,1.7471,1.6471,1.5471};
//构造系数矩阵
double[] x=new double[4];
i=g.cagaus(a,b,4,x);

if(i!=0)
for(i=0;i<=3;i++)
System.out.println("x("+i+")="+x[i]);

}
}

0

G_gauss 我想看看这个类的代码

0

x(0)=1.0405766794193478

x(1)=0.9870507683921363

x(2)=0.9350403339335612

x(3)=0.8812823294843842