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

标签 c# math types double decimal

我想知道以上是否完全可行。例如:

Math.Sqrt(myVariableHere);

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

最佳答案

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

有几种方法可以根据数字计算平方根。其中之一是由艾萨克·牛顿提出的。我只会编写此方法的最简单实现之一。我用它来提高 double 平方根的精度。

// 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;
}

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

如果您想了解更多信息,请阅读 this (Hacker's Delight by Henry S. Warren, Jr.)

关于c# - 在 C# 中对十进制数据类型执行数学运算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4124189/

相关文章:

c# - C#中如何从arraylist中获取对象

c# - Visual Studio 2010 项目到 Visual Studio 2012

function - 如何在 Matlab 中计算某个点的函数?

math - pow(0, 2.2) 在 hlsl 像素着色器中给出 1?

java - 我有一个带有 1 个 setter 方法的抽象类 - 参数是一个对象。我想要一个通用的 <T> 参数,它采用扩展它的类的类型

c# - 循环遍历数据表,获取值和标题

c# - SQL Server 和 C# WinForms 错误

python - 如何在 python 中获取特定数据集的内容类型(或变量类型)?

visual-studio - 如何使用序列在 F# 中创建无限集的幂集(组合)?

java - Java 中的数据类型及其表示