【问题标题】:C# Mathematics Calculation not working properlyC# 数学计算无法正常工作
【发布时间】:2010-10-30 23:35:42
【问题描述】:

好的,所以我在这里执行了一个烦人的数学计算,试图求解其中一个立方根。

现在,这是我的 C# 代码:

public void CubeCalculate()
{
    //Calculate discriminant

    double insideSquareRoot = (18 * cubicAValue * cubicBValue * cubicCValue * cubicDValue) + (-4 * (Math.Pow(cubicBValue, 3) * cubicDValue) + (Math.Pow(cubicBValue, 2) * Math.Pow(cubicCValue, 2)) + (-4 * cubicAValue * Math.Pow(cubicCValue, 3)) + (-27 * Math.Pow(cubicAValue, 2) * Math.Pow(cubicDValue, 2)));

    if (insideSquareRoot < 0)
    {
        //One real solution, two imaginary
        double onecuberootradical1 = (1 / 2) * (((2 * Math.Pow(cubicBValue, 3)) + (-9 * cubicAValue * cubicBValue * cubicCValue) + (27 * Math.Pow(cubicAValue, 2) * cubicDValue)) + (Math.Sqrt(Math.Pow((2 * Math.Pow(cubicBValue, 3)) + (-9 * cubicAValue * cubicBValue * cubicCValue) + (27 * Math.Pow(cubicAValue, 2) * cubicDValue), 2) + (-4 * Math.Pow(Math.Pow(cubicBValue, 2) + (-3 * cubicAValue * cubicCValue), 3)))));
        double onecuberootradical2 = (1 / 2) * (((2 * Math.Pow(cubicBValue, 3)) + (-9 * cubicAValue * cubicBValue * cubicCValue) + (27 * Math.Pow(cubicAValue, 2) * cubicDValue)) - (Math.Sqrt(Math.Pow((2 * Math.Pow(cubicBValue, 3)) + (-9 * cubicAValue * cubicBValue * cubicCValue) + (27 * Math.Pow(cubicAValue, 2) * cubicDValue), 2) + (-4 * Math.Pow(Math.Pow(cubicBValue, 2) + (-3 * cubicAValue * cubicCValue), 3)))));
        x1 = (-cubicBValue / (3 * cubicAValue)) + ((-1 / (3 * cubicAValue)) * (Math.Pow(onecuberootradical1, 1 / 3))) + (-1 / (3 * cubicAValue) * Math.Pow(onecuberootradical2, 1 / 3));
        x2 = double.NaN;
        x3 = double.NaN;
    }

好的,我正在尝试找出这里出了什么问题。

首先,由于这是 MVC 应用程序的一部分,我确保我的其他根工作正常,所以这纯粹是以下计算的错误,而不是其他任何地方的问题。

现在,我在这里检查了很多次,没有发现任何问题。

您可以在此处与正确的公式进行比较:

这是我试图在此处复制的 x1 根。

另外,如果你想知道same Wikiepdia article 的官方判别式,这里是:

你们有什么不对吗???

【问题讨论】:

    标签: c# math c#-4.0 polynomial-math


    【解决方案1】:

    这很明显:

    (1 / 2)
    

    当您应该使用浮点数时,您正在那里执行整数除法:

    (1 / 2.0)
    

    你没有向我们展示你的cubic*Value变量的声明,所以我假设它们是双精度的。

    【讨论】:

    • 谢谢,现在只是一个问题,是否每个数字常量都必须指定小数位才能让 C# 知道它是浮点数/双精度数?此外,这并没有完全解决我的问题..
    • @Boss 你也修复了你的两个 1/3 吗?
    • 是的,我在上面计算的每个数字都附加了.0。除非那很糟糕,我只需要为除法做那个......
    • 除法的结果将被提升为最高精度类型,因此两个操作数中只有一个需要是浮点数,但没有区别是两者都是.
    • 每当你进行除法时,你必须确保分子或分母是double(你可以使用3.0或2.0而不是3或@987654328来做到这一点@)。
    【解决方案2】:

    这是或应该是常见问题之一,答案是: 每个计算机科学家都应该了解浮点运算 (link)

    【讨论】:

      猜你喜欢
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-20
      • 2018-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多