我被要求创建一个正弦函数来创建我自己的库。我在互联网上查找了一些提示,并编写了此代码。但是当角度高于 122.4099 时,此功能不起作用。不知道如何处理。我将从我的库中发布我的部分代码。(我用了麦克劳林和泰勒系列。
#include "stdio.h"
#define pi 3.141592
double power(double a, int b) // Imagined function 1
{
double product=1;
int i=0;
if(b==0)
{
return 1;
}
for(; i<b ; i++)
{
product = product * a;
}
return product;
}
int factorial(int a) // Imagined function 3
{
if(a==0)
{
return 1;
}
return a * factorial(a-1);
}
double sinTrig(double angle)
{
double imgSet = 0;
double sum = 0;
int n = 0;
double x;
x = angle * pi/180;
do
{
imgSet = power(-1,n) * power(x,2*n+1) / (double)factorial(2*n+1);
sum = sum + imgSet;
n++;
}while(abs(imgSet) >= 0.00001);
printf("n The sine of %.3lf is :: sin(%.2lf) --> %.3lf", angle, angle, sum);
return sum;
}
你的问题实际上不在于代码,而在于它背后的数学。在你的正弦函数中,
double sinTrig(double angle)
{
double imgSet = 0;
double sum = 0;
int n = 0;
double x;
x = angle * pi/180;
do
{
imgSet = power(-1,n) * power(x,2*n+1) / (double)factorial(2*n+1);
sum = sum + imgSet;
n++;
}while(abs(imgSet) >= 0.00001);
printf("n The sine of %.3lf is :: sin(%.2lf) --> %.3lf", angle, angle, sum);
return sum;
}
正如您所说,您计算麦克劳林级数(也称为以 0 为中心的泰勒级数(。这意味着您的函数可以很好地近似于足够接近 0 的角度的正弦函数,但是当角度远离 0 时,误差会变大。
你的代码
int factorial(int a) // Imagined function 3
{
if(a==0)
{
return 1;
}
return a * factorial(a-1);
}
它是递归函数。
当a
值很大时,它会生成堆栈溢出。
当角度变得大值时,你计算大阶乘。 删除递归并使用不同的方法来计算阶乘。