Java实现lagrange 插值法

来源:互联网 发布:数据挖掘实战微盘 编辑:程序博客网 时间:2024/05/01 23:45

一、题目:已知

1、请用两点 Lagrange插值 编程实现 ,用余项公式求误差;

1.1)程序源代码

public class Chazhi {public static void main(String[] args) {lagrange();}public static void lagrange() {double p = Math.atan(1) * 4;double[] x = { p / 4, p / 3, (5 * p) / 18 };double[] y = { Math.sqrt(2.0) / 2, Math.sqrt(3.0) / 2 };double l = 0.0;for (int j = 0; j < 2; j++) {double s = 1.0;for (int i = 0; i < 2; i++) {if (i != j)s = s * ((x[2] - x[i]) / (x[j] - x[i]));}l = l + s * y[j];}double m = (Math.abs(x[0]) / 2)* Math.abs((x[2] - x[0]) * (x[2] - x[1]));System.out.println("x=" + x[2]);System.out.println("L=" + l);System.out.println("误差为:" + m);}}

1.2)程序结果:


2、请用三点 lagrange 插值 编程实现,用余项公式求误差;

2.1)程序源代码:


public class Chazhi {public static void main(String[] args) {// lagrange();lagrange_2();}public static void lagrange_2() {double p = Math.atan(1) * 4;double[] x = { p / 6, p / 4, p / 3, (5 * p) / 18 };double[] y = { 0.5, Math.sqrt(2.0) / 2, Math.sqrt(3.0) / 2 };double l = 0.0;for (int j = 0; j < 3; j++) {double s = 1.0;for (int i = 0; i < 3; i++) {if (i != j)s = s * ((x[3] - x[i]) / (x[j] - x[i]));}l = l + s * y[j];}double M = (Math.abs(x[0]) / (2 * 3))* Math.abs((x[3] - x[0]) * (x[3] - x[1]) * (x[3] - x[2]));System.out.println("x=" + x[3]);System.out.println("L=" + l);System.out.println("误差为:" + M);}}


原创粉丝点击