我被要求通过创建自己的库来制作正弦函数。我在互联网上查找了一些提示,然后编写了这段代码。但当角度大于 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;
}
正如您所说,您计算的是 MacLaurin 级数(也称为以 0 为中心的泰勒级数)。这意味着当角度足够接近 0 时,您的函数可以很好地逼近正弦函数,但当角度远离 0 时,误差会变大。
关于c - 如何在 C 的正弦函数中输入大于 122.409 的角度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59010673/