我用 C# 编写了这个函数来计算 sin(x)。但是当我尝试使用 x = 3.14 时,sin X 的打印结果是 NaN (不是数字), 但调试时,它非常接近0.001592653 该值不太大,也不太小。那么 NaN 怎么会出现在这里呢?
static double pow(double x, int mu)
{
if (mu == 0)
return 1;
if (mu == 1)
return x;
return x * pow(x, mu - 1);
}
static double fact(int n)
{
if (n == 1 || n == 0)
return 1;
return n * fact(n - 1);
}
static double sin(double x)
{
var s = x;
for (int i = 1; i < 1000; i++)
{
s += pow(-1, i) * pow(x, 2 * i + 1) / fact(2 * i + 1);
}
return s;
}
public static void Main(String[] param)
{
try
{
while (true)
{
Console.WriteLine("Enter x value: ");
double x = double.Parse(Console.ReadLine());
var sinX = sin(x);
Console.WriteLine("Sin of {0} is {1}: " , x , sinX);
Console.ReadLine();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
最佳答案
它失败了,因为 pow(x, 2 * i + 1)
和 fact(2 * i + 1)
最终都返回 Infinity
。
就我而言,当x = 4
、i = 256
时。
请注意,pow(x, 2 * i + 1)
= 4 ^ (2 * 257)
= 2.8763090157797054523668883052624395737887631663 × 10^309 - 一个大得离谱的数,刚刚超过了 double 的最大值,大约为 1.79769313486232 x 10 ^ 308。
您可能只想使用 Math.Sin(x)
另请注意 fact(2 * i + 1) = 513! =
an even more ridiculously large number
比 estimated number of atoms in the observable universe 大 10^1000
倍以上.
关于c# - 为什么 C# 中的 sin(x) 函数返回 NaN 而不是数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34802850/