牛顿法:
public double sqr(double n){ double x=n,y=0.0; while (Math.abs(x-y)>0.0001){ y=x; x=(x+n/x)/2; } return x; }
设r是f(x) = 0的根,选取x0作为r初始近似值,过点(x0,f(x0))做曲线y = f(x)的切线L,L的方程为y = f(x0)+f‘(x0)(x-x0),求出L与x轴交点的横坐标 x1 = x0-f(x0)/f‘(x0),称x1为r的一次近似值。
过点(x1,f(x1))做曲线y = f(x)的切线,并求该切线与x轴交点的横坐标 x2 = x1-f(x1)/f‘(x1),称x2为r的二次近似值。重复以上过程,得r的近似值序列,其中x(n+1)=x(n)-f(x(n))/f‘(x(n)),称为r的n+1次近似值,上式称为牛顿迭代公式。
二分法:
#define eps 0.00001 float SqrtByDichotomy(float n) { if (n < 0) { return -1.0; } else { float low, up, mid, last; low = 0, up = (n>=1?n:1); mid = (low + up) / 2; do { if (mid*mid>n) up = mid; else low = mid; mid = (up+low)/2; } while (fabsf(mid - last) > eps); return mid; }
原文地址:https://www.cnblogs.com/10zhang/p/10557649.html
时间: 2024-11-08 11:59:20