C ++或C Pow给出错误的结果
c++ or c pow giving wrong result
>我试图制作自己的 pow,但我得到错误的结果
IM 得到:2^3.3 = 16,这是错误的...为什么?
#include <iostream>
using namespace std;
double new_pow(double base, double power){
double result = 1;
for(int i = 0; i <= power; i++) {
result *= base;
}
return result;
}
int main (int argc, char * const argv[]) {
std::cout << new_pow(2,3.3) << endl;
return 0;
}
请帮我找到错误
错误是你的循环运行了 4 次,因为 4 次迭代不会超过 3.3。这就是为什么浮点幂是用对数实现的,而不是重复乘法。
伊格纳西奥的回答已经提到了使用对数。但我们最终还是使用了exp()
它又是一个库函数。因此,如果您根本不想使用库函数,那么您必须求助于泰勒扩展x^y
正如伊格纳西奥所提到的,对泰勒x^y
扩张的直接评估是乏味的,base^power = exp( power*ln(base) )
。泰勒对 e^x 的展开非常简单,而对 ln(x( 的展开也非常简单。它们都可用于 C 语言中的简单交互/递归实现
这是使用上述泰勒扩展的e^x
的简单实现
double pow_x ( double x , unsigned i )
{
double prod=1;
if ( i == 0 )
return 1;
while ( i )
{
prod*=x;
i--;
}
return prod;
}
long long factorial ( unsigned n )
{
if ( n == 0 )
return 1;
return n * factorial (n-1);
}
// Function to calculate e^x. Hence expo(5, 20) is calculating
// e^5 by summing 20 terms from the infinite series expansion
// and NOT a power calculation of 5^20
double expo ( double x, int terms )
{
/* terms tells us how long should we expand the taylor's series */
double sum=0;
unsigned i=0;
while ( i< terms )
{
sum+= pow_x(x,i)/factorial(i);
i++;
}
return sum;
}
exp(5.93,20)
给出了谷歌倾向于同意的376.152869
。
我希望,使用此示例,您可以自己实现ln(x)
。
因为你i
递增 1。 所以在4.0
之后,它会直接递增到5.0
,从而使循环的条件检查为假,从而终止循环。
另外,循环变量的起始值是 0
,所以你应该像这样检查它 -
for(double i=0; i<power; i++)
你可以看看这个答案来了解如何实现浮点幂,并在这里获得相当高级的实现。
for(int i = 0; i <= power; i++)
应该是
for(int i = 1; i <= power; i++)
否则,它将运行一次额外的迭代。
正如伊格纳西奥·巴斯克斯-亚伯兰的回答中提到的。假设你想要功率 y = x^b。这相当于 ln(y( = b*ln(x(。
所以y = exp(b*ln(x))
y = Math.e(b*Math.Log(x)) //Java
通过将power
视为int
来循环。循环将运行 4 次并返回 2^4 = 16
。
如何使用对数近似十进制指数。
相关文章:
- 如何修复循环中的错误产生的错误结果?
- 添加可变参数函数的错误结果
- 使用特征 3 线性系统求解器的错误结果
- 按位包含 OR 的错误结果
- 如果我将索引变量更改为零,并且合并函数中的k = 0,则获得合并排序的错误结果
- STD :: FPCLASSIFY的错误结果使用Valgrind进行长时间的双重双重结果
- 视觉工作室的错误结果
- 将C#struct传递给C 不受管理的DLL返回错误结果
- 最长的常见子字错误结果
- 华氏度到摄氏度的错误结果
- UE4中简单坐标变换的错误结果
- 记忆错误结果的说明[编译器行为]
- 如何解决错误PRJ0002:错误结果 -1073741515从"cl.exe"返回?
- 错误 PRJ0002:错误结果 -1073741515 从"C:\Program Files\Microsoft Visual Studio 9.0\VC\bin\cl.
- glGetUniformLocation OpenGL ES 2.0(在ipad 3 iOS 7.0.3上返回错误结果)
- 在模板函数中调用std::for_each时出现错误结果
- 使用copy和back_inserter将矢量附加到其自身时出现错误结果
- CUDA 线程在全局内存中的私有位置写入时出现错误结果
- 来自 c++ 代码的错误结果
- 使用浮点值和铸造的算术运算的错误结果 - 差异很大,我想这不是准确值的情况(429497)?