Java实现牛顿法和弦截法
写个数值分析作业用计算器算起来太麻烦咯,还是写些代码自动化一下
package test;
public class mathHomework
{
public static void main(String[] args)
{
double x0 = 2;
double x1 = 0.6;
newtonInteration(x0, 10);
newtonXiashanInteration(x0, 3, 10);
// xianjieInteration(0.5,0.6,10);
myInteration(x0, 10);
}
/**
* 自己写的递推关系式
*
* @param x
* @param repeat
* @return
*/
public static double interationFunc(double x)
{
return x - (Math.pow(x, 3) - 5) / (3* x * x);
}
/**
* 函数表达式
*
* @param x
* @return
*/
public static double func(double x)
{
// return x - Math.pow(Math.E, -x);
return Math.pow((Math.pow(x, 3) - 5), 2);
}
/**
* 导数表达式
*
* @param x
* @return
*/
public static double diffFunc(double x)
{
// return 1 + Math.pow(Math.E, -x);
return 2 * (Math.pow(x, 3) - 5) * 3 * x * x;
}
/**
* 牛顿迭代法
*
* @param x0
* @param times
* @param flag:使用自己的迭代函数
*/
public static void newtonInteration(double x0, int times)
{
double xi = x0;
double xi1;
System.out.println("---------------------牛顿迭代法------------------------");
for (int i = 0; i < times; i++)
{
xi1 = xi - func(xi) / diffFunc(xi);
System.out.println("x" + (i + 1) + "=" + xi1);
xi = xi1;
}
}
/**
* 牛顿下山法
*
* @param x0
* @param times
*/
public static void newtonXiashanInteration(double x0, int repeat, int times)
{
double xi = x0;
double xi1;
System.out.println("---------------------牛顿下山法------------------------");
for (int i = 0; i < times; i++)
{
xi1 = xi - repeat * func(xi) / diffFunc(xi);
System.out.println("x" + (i + 1) + "=" + xi1);
xi = xi1;
}
}
/**
* 弦截法
*
* @param x0
* @param x1
* @param times
*/
public static void xianjieInteration(double x0, double x1, int times)
{
double xi = x0;
double xi1 = x1;
double xi2;
System.out.println("---------------------弦截法------------------------");
for (int i = 0; i < times; i++)
{
xi2 = (xi1 - (xi1 - xi) * func(xi1) / (func(xi1) - func(xi)));
System.out.println("x" + (i + 2) + "=" + xi2);
xi = xi1;
xi1 = xi2;
}
}
public static void myInteration(double x0, int times)
{
double xi = x0;
double xi1;
System.out.println("---------------------自定义迭代法------------------------");
for (int i = 0; i < times; i++)
{
xi1 = interationFunc(xi);
System.out.println("x" + (i + 1) + "=" + xi1);
xi = xi1;
}
}
}
输出结果:
---------------------牛顿迭代法------------------------
x1=1.875
x2=1.799537037037037
x3=1.7569482000561527
x4=1.7340843825074606
x5=1.7221969740024148
x6=1.7161297191047062
x7=1.7130638529350126
x8=1.7115226812070843
x9=1.710750012637576
x10=1.7103631547521934
---------------------牛顿下山法------------------------
x1=1.625
x2=1.7592455621301775
x3=1.6873915918533813
x4=1.7217235565732205
x5=1.7042221021520378
x6=1.7128820411801964
x7=1.708530291010196
x8=1.7107006098678912
x9=1.7096140754736906
x10=1.7101569971813315
---------------------自定义迭代法------------------------
x1=1.75
x2=1.7108843537414966
x3=1.7099764289169748
x4=1.709975946676833
x5=1.709975946676697
x6=1.709975946676697
x7=1.709975946676697
x8=1.709975946676697
x9=1.709975946676697
x10=1.709975946676697