繼續我之前發布的問題如何提高函式 e^x 的精度
通過接受給出的建議,我對代碼進行了一些更改
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
long double exponential(long double x, long double n, long double p)
{
long double i = 1;
while (n > 0) // loop stops when becomes less than 0
i = i (x / p) * (exponential(x, n - 0.0001, p 1));
if (n < 0) // when n reaches 0 or becomes less than zero value of i will be returned
return i;
}
int main()
{
long double p, x, n;
scanf("%Lf", &x);
printf("math.h e^x = %lf\n", exp(x));
printf("calculated e^x = %Lf\n", exponential(x, 1, 1));
return 0;
}
但我沒有得到任何輸出,它只是給出運行時錯誤(http://codepad.org/jIKoYGFC),我不知道為什么。請有人幫助我為什么會收到這些錯誤
uj5u.com熱心網友回復:
這個回圈完全是假的。您不是在撰寫迭代函式(它會更有意義)。此外,您還有一個零回傳未定義內容的極端情況。
雖然我不建議使用浮點進行回圈控制,也不建議對遞回呼叫進行數千次呼叫,但您的代碼應該更像
long double exponential(long double x, long double n, long double p)
{
long double i = 1;
if (n > 0)
i = (x / p) * (exponential(x, n - 0.0001, p 1));
return i;
}
最終就是這樣:
long double exponential(long double x, long double n, long double p)
{
return 1 ((n > 0) ? (x / p) * exponential(x, n - 0.0001, p 1) : 0);
}
解決這個問題(無論哪種方式):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
long double exponential(long double x, long double n, long double p)
{
return 1 ((n > 0) ? (x / p) * exponential(x, n - 0.0001, p 1) : 0);
}
int main()
{
long double x = 5;
printf("math.h e^x = %Lf\n", expl(x));
printf("calculated e^x = %Lf\n", exponential(x, 1, 1));
return 0;
}
輸出
math.h e^x = 148.413159
calculated e^x = 148.413159
uj5u.com熱心網友回復:
出于好奇,使用LibGMP創建了一個版本,看看這是否會改善結果。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gmp.h>
#define BITS 128
上面的行平均尾數是 128 位和 64 位的指數。這是我基于 GMP 的功能:
void gmp_exponential(mpf_t * i, double x, double n, int p)
{
mpf_t ii;
mpf_init(ii);
mpf_set_d(ii,1);
if (n > 0){
mpf_t a,b,c;
gmp_exponential(&ii, x, n - 0.0001, p 1);
mpf_inits (a, b, c, NULL);
mpf_set_d(a,x);
mpf_div_ui(b, a, p) ;
mpf_mul(c, b, ii);
mpf_add (*i,*i,c);
mpf_clears(a,b,c,NULL);
}
mpf_clear(ii);
}
重用WhozCraig的函式進行比較:
long double exponential(long double x, long double n, long double p)
{
return 1 ((n > 0) ? (x / p) * exponential(x, n - 0.0001, p 1) : 0);
}
以及運行它的代碼:
int main()
{
double x = 30.0;
mpf_t i;
mpf_init2 (i, BITS);
mpf_set_d(i,1);
gmp_exponential(&i, x, 1, 1);
printf ("math.h e^x = %Lf\n", expl(x));
gmp_printf ("calculated e^x with mpf = %.*Ff\n", 6, i);
printf ("calculated e^x = %Lf\n", exponential(x, 1, 1));
mpf_clear(i);
return 0;
}
輸出:
math.h e^x = 10686474581524.462147
calculated e^x with mpf = 10686474581524.462143
calculated e^x = 10686474581524.462149
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/435107.html
下一篇:遞回查找網格中的所有路徑
