有什么方法可以在不使用math.h和sqrt()的情况下获得数字的平方根?

Hot*_*ace 2 c math

我已经为使用MPI执行Fox的块矩阵乘法方法的类编写了一个程序。我能够通过在中使用sqrt()函数来做到这一点,但是为了编译程序,我必须输入“ mpicc -lm -o ...”。有关hw状态的说明,可使用“ mpicc -o ...”而不使用-lm来编译程序。我只是想知道是否有一种方法可以找到数字的平方根(无需编写单独的程序即可)。如果没有,我将免责声明放在.txt文件顶部的注释中。以为这可能是个好地方。谢谢!

Wea*_*ane 6

该方法使用逐次逼近。它不需要很多迭代。因为root可以抖动的值,所以我将收敛性检查为一个很小的误差。

//#define MINDIFF 2.2250738585072014e-308   // smallest positive double
#define MINDIFF 2.25e-308                   // use for convergence check

double sqroot(double square)
{
    double root=square/3, last, diff=1;
    if (square <= 0) return 0;
    do {
        last = root;
        root = (root + square / root) / 2;
        diff = root - last;
    } while (diff > MINDIFF || diff < -MINDIFF);
    return root;
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以通过重复固定的次数来更简单地执行此操作

double sqroot(double square)
{
    double root=square/3;
    int i;
    if (square <= 0) return 0;
    for (i=0; i<32; i++)
        root = (root + square / root) / 2;
    return root;
}
Run Code Online (Sandbox Code Playgroud)


Tal*_*rom 5

有一个用于计算1 / sqrt的旧计算机图形技巧:(来自Quake III的原始代码)

    float Q_rsqrt( float number ) {
      long i;
      float x2, y;
      const float threehalfs = 1.5F;

      x2 = number * 0.5F;
      y  = number;
      i  = * ( long * ) &y;                       // evil floating point bit level hacking
      i  = 0x5f3759df - ( i >> 1 );               // what is this?
      y  = * ( float * ) &i;
      y  = y * ( threehalfs - ( x2 * y * y ) );   // 1st iteration
      //      y  = y * ( threehalfs - ( x2 * y * y ) );   // 2nd iteration, this can be removed
        return y;
    }
Run Code Online (Sandbox Code Playgroud)

您可以在这里阅读所有内容

顺便说一句,我建议您只使用编译标志...