在C#中对十进制数据类型执行数学运算?

Qco*_*com 17 c# math double types decimal

我想知道上述情况是否完全可能.例如:

Math.Sqrt(myVariableHere);
Run Code Online (Sandbox Code Playgroud)

在查看重载时,它需要一个double参数,所以我不确定是否有另一种方法可以使用decimal数据类型复制它.

SLe*_*nik 53

我不明白为什么这个问题的所有答案都是一样的.

有几种方法可以从数字中计算平方根.其中一个是艾萨克·牛顿提出的.我只会写一个这个方法最简单的实现.我用它来提高双平方根的准确性.

// x - a number, from which we need to calculate the square root
// epsilon - an accuracy of calculation of the root from our number.
// The result of the calculations will differ from an actual value
// of the root on less than epslion.
public static decimal Sqrt(decimal x, decimal epsilon = 0.0M)
{
    if (x < 0) throw new OverflowException("Cannot calculate square root from a negative number");

    decimal current = (decimal)Math.Sqrt((double)x), previous;
    do
    {
        previous = current;
        if (previous == 0.0M) return 0;
        current = (previous + x / previous) / 2;
    }
    while (Math.Abs(previous - current) > epsilon);
    return current;
}
Run Code Online (Sandbox Code Playgroud)

关于速度:在最坏的情况下(epsilon = 0且number为decimal.MaxValue),循环重复次数少于三次.

如果您想了解更多信息,请阅读本文(由Henry S. Warren,Jr.撰写的Hacker's Delight)


Mar*_*ell 5

在大多数涉及decimal(货币等)的情况下,扎根是没有的;并且根不会具有您可能期望 adecimal具有的预期精度。您当然可以通过强制转换来强制它(假设我们没有处理decimal范围的极端):

decimal root = (decimal)Math.Sqrt((double)myVariableHere);
Run Code Online (Sandbox Code Playgroud)

这迫使您至少承认固有的舍入问题。

  • 好吧,我正在制作一个应用程序来计算黄金比例,最终会进入小数范围。在我的场景中不起作用。 (5认同)

Bob*_*son 5

我刚刚遇到这个问题,我建议使用与 SLenik 提出的算法不同的算法。这是基于巴比伦方法

public static decimal Sqrt(decimal x, decimal? guess = null)
{
    var ourGuess = guess.GetValueOrDefault(x / 2m);
    var result = x / ourGuess;
    var average = (ourGuess + result) / 2m;

    if (average == ourGuess) // This checks for the maximum precision possible with a decimal.
        return average;
    else
        return Sqrt(x, average);
}
Run Code Online (Sandbox Code Playgroud)

它不需要使用现有Sqrt函数,因此避免了转换为double和返回,随之而来的精度损失。