package com.zhp.second.定点迭代;
public class PointIteration {
public static final double scale = 0.00000000001;
public static void main(String[] args) {
double startValue = 1.5;
System.out.println("x = √(2x),初值1.5, 定点迭代结果为:" + getResult(startValue));
}
public static double getNextValue(double x) {
return Math.sqrt(2 * x);
}
public static double getResult(double x) {
double nextValue = getNextValue(x);
if (Math.abs(nextValue - x) > scale) {
return getResult(nextValue);
}
return nextValue;
}
}
package com.zhp.second.牛顿法求根;
public class Newton {
final static double scale = 0.00001;
static Equation f;
public static void main(String[] args) {
double[] a = {1, -1, 2, 5};
f = new Equation(a);
double[] b = getB(f, -1);
double Bn = b[b.length - 1];
double Cn_1 = getCn_1(b, -1);
double result = getNextXk(-1, Bn, Cn_1);
System.out.println("方程:" + f.toString() + " 的解为:" + result);
}
// --------------
// 获得Bn
// --------------
public static double[] getB(Equation f, double Xk){
double[] b = new double[f.n];
b[0] = f.a[0];
for(int i = 1; i < f.n; i++){
b[i] = f.a[i] + b[i - 1] * Xk;
}
return b;
}
// --------------
// 获得C(n-1)
// --------------
public static double getCn_1(double[] b, double Xk){
double[] c = new double[b.length - 1];
c[0] = b[0];
for(int i = 1; i < c.length; i++){
c[i] = b[i] + Xk * c[i - 1];
}
return c[c.length - 1];
}
// --------------
// 迭代计算
// --------------
public static double getNextXk(double Xk, double Bn, double Cn_1){
if(Math.abs(Bn) <= scale){
return Xk;
}
double nextValue = Xk - Bn / Cn_1;
double nextBn = getB(f, nextValue)[f.n - 1];
double nextCn_1 = getCn_1(getB(f, nextValue), nextValue);
return getNextXk(nextValue, nextBn, nextCn_1);
}
}
package com.zhp.second.正割法;
public class Secant {
public static final double scale = 0.00001;
public static void main(String[] args) {
double temp = getResult(0.5, 0.6);
System.out.println("正割法结果为:" + temp);
}
public static double F(double x) {
return x * Math.pow(Math.E, x) - 1;
}
public static double getNextValue(double Xk, double Xk_1) {
return Xk - F(Xk) / (F(Xk) - F(Xk_1)) * (Xk - Xk_1);
}
public static double getResult(double Xk_1, double Xk) {
double nextXk = getNextValue(Xk, Xk_1);
if (Math.abs(nextXk - Xk) <= scale)
return nextXk;
else
return getResult(Xk, nextXk);
}
}