牛顿迭代法求高精度开方
来源:互联网 发布:aix 安装软件 编辑:程序博客网 时间:2024/05/16 11:28
牛顿迭代法:http://baike.baidu.com/view/643093.htm
牛顿迭代公式:x(n+1)=x(n)-f(x(n))/f'(x(n))
如求2的平方根,构造函数 x^2 - 2 = 0;
dif为精度, 如果精度小于dif 跳出程序。这样可求出简单的平方根
- import java.math.BigDecimal;
- import java.math.MathContext;
- import java.math.RoundingMode;
- public class sqrt{
- public static void main(String[] args){
- // x^2 -2 = 0
- BigDecimal x1 = new BigDecimal(1);
- BigDecimal x2 = new BigDecimal(0);
- BigDecimal dif = new BigDecimal(0);
- BigDecimal precision = new BigDecimal(0.000000000000000000000000000000000000000000000000001);
- while(true){
- x2 = x1.subtract(x1.pow(2).subtract(new BigDecimal(2)).divide(x1.multiply(new BigDecimal(2)),100, BigDecimal.ROUND_HALF_EVEN));
- if(x1.compareTo(x2)==1){
- dif = x1.subtract(x2);
- }else{
- dif = x2.subtract(x1);
- }
- if(dif.compareTo(precision)==-1){
- System.out.println(x1+","+x2);
- break;
- }
- x1 = x2;
- }
- }
- }
如果要求高精度,而 怎样确定dif小于小数点后100位?
使用java提供的大数类,后程序变为
- public class sqrt{
- public static void main(String[] args){
- // x^2 -2 = 0
- double x1=1,x2=0;
- double dif=0;
- while(true){
- x2 = x1 - (x1*x1-2)/(2*x1);
- if(x2>x1){
- dif = x2-x1;
- }else{
- dif = x1-x2;
- }
- if(dif<0.000000000001){
- System.out.println(x1+","+x2);
- break;
- }
- x1 = x2;
- }
- }
- }
其中大数运算中出现除不尽的异常,后直接控制了位数,保留100位。
现在的问题是,如何确定精度dif是100,也就是怎样用Java表示出0.000……1 (小数点后100位)
考虑了很久,其实可以用 大数运算 用1除10的100次方。
改进代码如下:
- import java.math.BigDecimal;
- import java.math.MathContext;
- import java.math.RoundingMode;
- public class sqrt{
- public static void main(String[] args){
- // x^2 -2 = 0
- BigDecimal x1 = new BigDecimal(1);
- BigDecimal x2 = new BigDecimal(0);
- BigDecimal dif = new BigDecimal(0);
- BigDecimal precision =x1.divide(new BigDecimal(10).pow(100));
- System.out.println(precision);
- while(true){
- x2 = x1.subtract(x1.pow(2).subtract(new BigDecimal(2)).divide(x1.multiply(new BigDecimal(2)),100, BigDecimal.ROUND_HALF_EVEN));
- if(x1.compareTo(x2)==1){
- dif = x1.subtract(x2);
- }else{
- dif = x2.subtract(x1);
- }
- if(dif.compareTo(precision)==-1){
- System.out.println(x1+","+x2);
- break;
- }
- x1 = x2;
- }
- }
- }
0 0
- 牛顿迭代法求高精度开方
- 牛顿迭代法求高精度开方
- 牛顿迭代法求开方
- 牛顿迭代法求开方值
- java 实现 牛顿迭代法求开方
- 通俗易懂地讲解牛顿迭代法求开方
- leetcode:Sqrt(x) 牛顿迭代法求整数开方
- leetcode 69. Sqrt(x)(C语言,牛顿迭代法求开方问题)46
- 牛顿迭代法求平方根
- 牛顿迭代法求平方根
- 牛顿迭代法求平方根
- 牛顿迭代法求平方根
- 牛顿迭代法求平方根
- 牛顿迭代法求方根
- 牛顿迭代法求平方根
- 牛顿迭代法求平方根
- 牛顿迭代法求平方根
- 牛顿迭代法 求 根
- 注册表保护
- 标题: 黄金连分数
- QT访问Mysql数据库
- JAVA 反射机制
- 傅里叶变换的物理意义
- 牛顿迭代法求高精度开方
- 你不知道的JavaScript(五)内置对象模版
- Java 类中的初始化顺序一
- CornerStone简单配置及使用
- 3DES-待完善
- 文件保护 miniflter
- python 利用 setup.py 手动安装第三方类库 - cocoajin
- AVI 视频编码
- 仿新浪微博IOS客户端(v5.2.8)——搭建项目基本框架