********************************
鉴于在博客中写公式略显难看,有碍观瞻,博客中的内容我都事先用latex写了一个pdf的文档,可以在下链接下载
http://download.youkuaiyun.com/detail/xue_haiyang/7640513
下面所写的难免有各种错误,还请留言批评指正(欢迎任意的批评交流)
********************************
上篇博客(http://blog.youkuaiyun.com/xue_haiyang/article/details/37960863)
给出了关于单变量方程近似解的解法的四个方法,这里
给出Java的具体实现和两个方程 的根的实例
最后给出这几个方法逼近速度的比较
代码实例
二分法
方程
public class BiSection {
public static void main(String[] args)
{
double temp =(double)1.4142137222;
System.out.print(temp+"\n");
double y= (double)1.0;
double a=1;
double b=10;
for (int i=2; i<300; i++){
y=(a+b)/((double)2.0);
if (y*y-(double)2.0>0)
{
b=y;
} else
a=y;
// System.out.print(i+"\n");
System.out.print(y+"\n");
// System.out.print(temp*temp+"\n");
}
}
}
方程
//Xue Haiyang at 2014.7.19
public class Bisection {
public static void main(String[] args)
{
double temp=1.0;
// System.out.print(temp+"\n");
double y= (double)1.0;
double a=1;
double b=10;
for (int i=2; i<300; i++){
y=(a+b)/((double)2.0);
temp=y*y*y+4*y*y-9;
System.out.print(a+"|");
System.out.print(y+"|");
System.out.print(b+"\n");
if (temp>0)
{
b=y;
} else
a=y;
}
}
}
不动点
// Xue Haiyang at 2014.7.19
public class Fixpoint {
public static void main(String[] args)
{
double y= (double)2.0;
for (int i=2; i<300; i++){
System.out.print(y+"\n");
y=0.5*Math.sqrt(9-y*y*y);
}
}
}
牛顿法
方程
//Xue Haiyang at 2014.7.19
public class NewtonRoot {
public static void main(String[] args)
{
double y= (double)10.0;
for (int i=2; i<300; i++){
y=(y*y+(double)2.0)/((double)2.0*y);
// System.out.print(i+"\n");
System.out.print(y+"\n");
// System.out.print(temp*temp+"\n");
}
}
}
方程
//Xue Haiyang at 2014.7.19
public class Newton {
public static void main(String[] args)
{
double y= (double)10.0;
for (int i=2; i<30; i++){
y=y-(y*y*y+4*y*y-9)/((double)3.0*y*y+8*y);
System.out.print(y+"\n");
}
}
}
割线法
方程
//Xue Haiyang at 2014.7.19
public class Secant {
public static void main(String[] args)
{
double y= (double)10.0;
double y1=y-(y*y*y+4*y*y-9)/((double)3.0*y*y+8*y);
double y2= (double)1.0;
for (int i=2; i<30; i++){
y2=y1-(y1*y1*y1+4*y1*y1-9)/(y1*y1+y1*y+y*y+4*y+4*y);
y=y1;
y1=y2;
// System.out.print(i+"\n");
System.out.print(y1+"\n");
// System.out.print(temp*temp+"\n");
}
}
}
逼近速度比较
方程 
方程 
下面是几种方法的数据其中 B-a B_b 是二分法中的区间,B_y是中间值。 牛顿最快割线法次之。
下面是图形展示