如何提高函数 e^x 的精度
How to increase precision for function e^x
我正在学习 C,我被要求计算 e^x 并将其与 math.h 中 exp 函数给出的值进行比较
这就是我所做的:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
double exponential( double x , double n, double p ){
double i=1;
if(n<0)
return i;
else
i=i+(x/p)*(exponential(x,n-0.00001,p+1));}
int main(){
double x,n,p;
scanf("%lf",&x);
printf("math.h e^x = %lf\n",exp(x));
printf("calculated e^x = %lf\n",exponential(x,1,1));
return 0;}
但我只得到 x = 30 的正确答案,之后随着我增加 x,它的偏差更大。谁能告诉我应该如何更改代码以提高精度。
您的代码有未定义的行为(比较 If a function returns no value, with a valid return type, is it okay to for the compiler to return garbage?)。
这就是任何不需要或意外行为所需的全部解释。
比较 What is Undefined Behaviour in C? .
我正在学习 C,我被要求计算 e^x 并将其与 math.h 中 exp 函数给出的值进行比较 这就是我所做的:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
double exponential( double x , double n, double p ){
double i=1;
if(n<0)
return i;
else
i=i+(x/p)*(exponential(x,n-0.00001,p+1));}
int main(){
double x,n,p;
scanf("%lf",&x);
printf("math.h e^x = %lf\n",exp(x));
printf("calculated e^x = %lf\n",exponential(x,1,1));
return 0;}
但我只得到 x = 30 的正确答案,之后随着我增加 x,它的偏差更大。谁能告诉我应该如何更改代码以提高精度。
您的代码有未定义的行为(比较 If a function returns no value, with a valid return type, is it okay to for the compiler to return garbage?)。
这就是任何不需要或意外行为所需的全部解释。
比较 What is Undefined Behaviour in C? .