牛顿迭代法求解根的问题

牛顿迭代法的公式

xk+1=xk-f(x)/f(x)’;
而利用牛顿迭代法往往是求一个近似值。精度一般达到1*10-5。不同的问题迭代条件要具体讨论。
下面给出两个例子

1.在Java中用自定义的接口方法求一个双精度数的立方根。

源代码

package nowcoderPractice;
import java.lang.Math;
import java.util.Scanner;
interface Root{
    public static double getCubeRoot(double input)
    {
        double x=1.0;
        for(;Math.abs(Math.pow(x,3.0)-input)>1e-5;x=x-((Math.pow(x,3.0)-input)/(3*Math.pow(x,2.0))));
        return x;
    }
}
public class Lifanggen implements Root{
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        double num=sc.nextDouble();
        System.out.println(String.format("%.1f", Root.getCubeRoot(num)));
        sc.close();
    }
}

可以看到输入一个数求这个数的立方根,这是求一个近似值,所以需要x3与输入数input的差在1*10-5内。故迭代条件为Math.abs(Math.pow(x,3.0)-input)>1e-5.

2.在C语言中求ax3+bx2+cx+d=0在1附近的一个实根。abcd由键盘输入。

源代码

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
double niuDun(double a,double b,double c,double d);
int main()
{
	int a, b, c, d;
	printf("请输入方程参数a,b,c,d\n");
	scanf_s("%d%d%d%d", &a, &b, &c, &d);
	printf("%lf", niuDun(a, b, c, d));
	return 0;
}
double niuDun(double a, double b, double c, double d)
{
	double f, fd,s,x=1.5;
	double x0;
	do
	{
		x0 = x;
		f = a * (double)pow(x, 3) + b * (double)pow(x, 2) + c * x + d;
		fd = 3 * a * (double)pow(x, 2) + 2 * b * x + c;
		s = f / fd;
		x = x0 - s;
	} while (abs(x - x0) > 1e-5);
	return x;
}

可以看到这里是求方程在1附近的实根,故迭代条件是x-x0>=1e-5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

玖语巴黎

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值