- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我在不使用 sqrt 函数的情况下找出求平方根的算法,然后尝试将其用于编程。我最终在 C++ 中得到了这个工作代码
#include <iostream>
using namespace std;
double SqrtNumber(double num)
{
double lower_bound=0;
double upper_bound=num;
double temp=0; /* ek edited this line */
int nCount = 50;
while(nCount != 0)
{
temp=(lower_bound+upper_bound)/2;
if(temp*temp==num)
{
return temp;
}
else if(temp*temp > num)
{
upper_bound = temp;
}
else
{
lower_bound = temp;
}
nCount--;
}
return temp;
}
int main()
{
double num;
cout<<"Enter the number\n";
cin>>num;
if(num < 0)
{
cout<<"Error: Negative number!";
return 0;
}
cout<<"Square roots are: +"<<sqrtnum(num) and <<" and -"<<sqrtnum(num);
return 0;
}
现在的问题是在声明中初始化迭代次数 nCount(这里是 50)。例如求 36 的平方根需要 22 次迭代,所以没有问题,而求 15625 的平方根需要 50 多次迭代,所以它会在 50 次迭代后返回 temp 的值。请给出解决方案。
最佳答案
有一种更好的算法,最多需要 6 次迭代才能收敛到 double 的最大精度:
#include <math.h>
double sqrt(double x) {
if (x <= 0)
return 0; // if negative number throw an exception?
int exp = 0;
x = frexp(x, &exp); // extract binary exponent from x
if (exp & 1) { // we want exponent to be even
exp--;
x *= 2;
}
double y = (1+x)/2; // first approximation
double z = 0;
while (y != z) { // yes, we CAN compare doubles here!
z = y;
y = (y + x/y) / 2;
}
return ldexp(y, exp/2); // multiply answer by 2^(exp/2)
}
算法从 1 开始,作为平方根值的第一近似值。然后,在每一步,它通过取当前值 y
之间的平均值来改进下一个近似值。和 x/y
.如果 y
= sqrt(x)
,它会是一样的。如果 y
> sqrt(x)
,然后 x/y
< sqrt(x)
大约相同的数量。换句话说,它会很快收敛。
更新:为了加快在非常大或非常小的数字上的收敛速度,更改了 sqrt()
从[1, 4)
中的数字提取二进制指数并计算平方根的函数范围。它现在需要 frexp()
来自 <math.h>
获得二进制指数,但可以通过从 IEEE-754 数字格式中提取位而不使用 frexp()
来获得该指数.
关于c++ - 不使用 sqrt 函数求平方根?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19611198/
出于某种原因,我的平方根程序得到的答案与大多数输入应得到的答案略有不同。我不确定这是为什么。只有某些输入是错误的。在给出答案后的最后我也遇到了段错误,我不确定为什么会这样。 #include #inc
我目前正在实现一个可以处理与物理单位相关的数字数据的类。 我想实现一种计算实例平方根的方法。假设您有一个具有属性值和名称的类的实例: from math import sqrt class Foo:
我正在使用 HTML + CSS + AngularJS 制作一个简单的计算器。一切正常,但我想添加一个 SquareRoot 函数。这是一些代码: function _solve(){ switc
问题是关于在通用数值接口(interface)中定义平方根算法的问题的策略方法。我知道存在解决不同条件下问题的算法。我对以下算法感兴趣: 仅使用选定的函数解决问题; 不关心操作的对象是整数、 floa
好吧,我已经研究了一段时间了,我知道我的逻辑是正确的,但是,我似乎无法生成正数的正确底平方根。 public int mySqrt(int x) { if(x 0) uppe
我找不到让这个函数 Math.sqrt(value) 工作的方法。 (╯°□°)╯︵┻━┻我不确定,但问题似乎出在运营商。我还尝试在 const calculation 中添加该函数,但它也不起作用。
我发现了这段获得平方根的代码,令我惊讶的是它的工作方式,使用 union 和位移这是代码: float sqrt3(const float x) { union { int i;
在 python 中使用 sqrt 函数时,我遇到了“distance ValueError: math domain error”问题。 这是我的代码: from math import sqrt
我一直在做一些研究,寻找一种对大整数进行运算的相对快速的平方根算法。我在这里找到了几个例程。第一个(下面)是用 C 语言编写的... int isqrt(int n) { int b = 0;
好吧,我想知道 math.h 平方根与其中包含神奇数字的那个(因 Quake 而出名,但由 SGI 制作)相比有多快。 但这对我来说是一个受伤的世界。 我首先在 Mac 上尝试了此操作,其中 math
有谁知道如何解决这个复发? 大定理在这里不起作用。 最佳答案 这在 O(1) 中似乎很明显,因为 T(n) = T(n - sqrt(n)) = T(m) with 0 < m < n 通过归纳,你得
我是一名优秀的程序员,十分优秀!