c# - 为什么 C# 中的 sin(x) 函数返回 NaN 而不是数字

标签 c# loops double nan trigonometry

我用 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 = 4i = 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 numberestimated number of atoms in the observable universe10^1000 倍以上.

关于c# - 为什么 C# 中的 sin(x) 函数返回 NaN 而不是数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34802850/

相关文章:

javascript - 尝试创建一个 for 循环来记录数组中的偶数

java - 平均前导零

c# - 将凹包算法转换为 C#

c# - 模拟对象在单元测试中为空

c# - 如何使用 RegEx 删除可能嵌套的括号?

c++ - 如何使用循环清理此代码?

PHP foreach重复循环问题

c# - VS2022 - 输入问题

谁能解释一下输出

java - 返回传递的字符串的 double 值