gpt4 book ai didi

c - -nan 返回值/e(欧拉)提升到幂计算循环

转载 作者:行者123 更新时间:2023-11-30 14:50:06 27 4
gpt4 key购买 nike

我正在学习C编程,并制定了以下算法来解决这个问题:

Link to a pic of the problem.代码实际上有效,但最初循环只有 10 次重复(rep <= 10),p = 3 的答案几乎是正确的,所以我更改了rep <= 20。它给了我我的确切答案计算器。然后我尝试使用更大的数字 12,但输出再次不准确。所以我结束了提高rep <= 35。如果我得到更高重复的循环,我会得到“-nan”,如果p的输入太高,它将是相同的。因此,只需查看模式即可知道,当我输入较高的数字时,不准确的问题将会再次出现,但事实并非如此,因为如果我输入较高的值,输出将为 NaN。

是否可以在没有更高级别的函数的情况下解决它?只是想知道我的程序是否适合我现在的水平...

#include <stdio.h>

int main()
{
float p; //the power for e
float power; //the copy of p for the loop
float e = 1; //the e number I wanna raise to the power of p
int x = 1; //the starting number for each factorial generation
float factorial = 1;
int rep = 1; //the repeater for the loop

printf( "Enter the power you want to raise: " );
scanf( "%f", &p );

power = p;

while ( rep <= 35) {
while ( x > 1) {
factorial *= x;
x--;
}
e += p / factorial;

//printf("\nthe value of p: %f", p); (TESTER)
//printf("\nthe value of factorial: %f", factorial); (TESTER)

p *= power; //the new value for p
rep++;
factorial = 1;
x = rep; //the new value for the next factorial to be generated

//printf("\n%f", e); (TESTER)
}
printf("%.3f", e);

return 0;
}

抱歉,如果我有语法/拼写错误,我仍在学习该语言。

最佳答案

在开始之前,让我们将原始代码编写为函数,并进行一些清理:

float exp_original(float x, int rep = 35)
{
float sum = 1.0f;
float power = 1.0f;
for (int i = 1; i <= rep; i++)
{
float factorial = 1.0f;
for (int j = 2; j <= i; j++)
factorial *= j;
power *= x;
sum += power / factorial;
}
return sum;
}

您使用了一些不必要的变量,这些变量已被删除,但除此之外,过程是相同的:从头开始计算阶乘。

<小时/>

让我们看看级数中连续项之间的比率:

enter image description here

因此,我们可以简单地将当前项乘以该表达式即可得到下一个项:

float exp_iterative(float x, int rep = 35)
{
float sum = 1.0f;
float term = 1.0f;
for (int i = 1; i <= rep; i++)
{
term *= x / i;
sum += term;
}
return sum;
}

看起来更简单,但是更好吗?与 C 库 exp 函数的比较(我们假设它是最精确的):

x   exp (C)       exp_orig    exp_iter
-------------------------------------------
1 2.7182817 2.718282 2.718282
2 7.3890562 7.3890567 7.3890567
3 20.085537 20.085539 20.085539
4 54.598148 54.598152 54.598152
5 148.41316 148.41318 148.41316
6 403.4288 403.42871 403.42877
7 1096.6332 1096.6334 1096.6334
8 2980.958 2980.9583 2980.9587
9 8103.084 8103.083 8103.083
10 22026.465 22026.467 22026.465
11 59874.141 59874.148 59874.152
12 162754.8 162754.77 162754.78
13 442413.41 -nan(ind) 442413.38
14 1202604.3 -nan(ind) 1202603.5
15 3269017.3 -nan(ind) 3269007.3
16 8886111 -nan(ind) 8886009
17 24154952 -nan(ind) 24153986
18 65659968 -nan(ind) 65652048
19 1.784823e+08 -nan(ind) 1.7842389e+08
20 4.8516518e+08 -nan(ind) 4.8477536e+08

这两个自定义实现在精度方面不相上下,直到 x = 13,而原始实现给出 NaN。这是因为最高幂项 13^35 = 9.7278604e+38 超过了最大值 FLT_MAX = 3.40282e+38。迭代版本中的累积项永远不会达到极限。

关于c - -nan 返回值/e(欧拉)提升到幂计算循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49211243/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com