相关疑难解决方法(0)

浮点数学是否破碎?

请考虑以下代码:

0.1 + 0.2 == 0.3  ->  false
Run Code Online (Sandbox Code Playgroud)
0.1 + 0.2         ->  0.30000000000000004
Run Code Online (Sandbox Code Playgroud)

为什么会出现这些不准确之处?

language-agnostic math floating-point floating-accuracy

2798
推荐指数
28
解决办法
28万
查看次数

实现基于整数的幂函数pow(int,int)的最有效方法

将整数提升到C中另一个整数的幂的最有效方法是什么?

// 2^3
pow(2,3) == 8

// 5^5
pow(5,5) == 3125
Run Code Online (Sandbox Code Playgroud)

c algorithm math exponentiation

239
推荐指数
8
解决办法
19万
查看次数

为什么pow(int,int)这么慢?

我一直在做一些项目Euler练习,以提高我对C++的知识.

我写了以下函数:

int a = 0,b = 0,c = 0;

for (a = 1; a <= SUMTOTAL; a++)
{
    for (b = a+1; b <= SUMTOTAL-a; b++)
    {
        c = SUMTOTAL-(a+b);

        if (c == sqrt(pow(a,2)+pow(b,2)) && b < c)
        {
            std::cout << "a: " << a << " b: " << b << " c: "<< c << std::endl;
            std::cout << a * b * c << std::endl;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这计算在17毫秒.

但是,如果我改变了这条线

if (c == sqrt(pow(a,2)+pow(b,2)) && b < …
Run Code Online (Sandbox Code Playgroud)

c++ performance cmath pow

48
推荐指数
2
解决办法
7428
查看次数

负指数平方的幂

我不确定平方的幂是否可以处理负指数。我实现了以下仅适用于正数的代码。

    #include <stdio.h>
    int powe(int x, int exp)
    {
         if (x == 0)
            return 1;
         if (x == 1)
            return x;
         if (x&1)
                return powe(x*x, exp/2);
         else
                return x*powe(x*x, (exp-1)/2);       
    }
Run Code Online (Sandbox Code Playgroud)

查看https://en.wikipedia.org/wiki/Exponentiation_by_squaring没有帮助,因为以下代码似乎是错误的。

    Function exp-by-squaring(x, n ) 
      if n < 0  then return exp-by-squaring(1 / x, - n );
      else if n = 0  then return  1;
      else if n = 1  then return  x ; 
      else if n is even  then return exp-by-squaring(x * x,  n / 2); …
Run Code Online (Sandbox Code Playgroud)

c algorithm math recursion

4
推荐指数
1
解决办法
3766
查看次数