在C#中对十进制数据类型执行数学运算?
我想知道上述情况是否完全可能。 例如:
Math.Sqrt(myVariableHere);
在查看重载时,它需要一个double参数,所以我不确定是否有另一种方法可以使用decimal数据类型复制它。
在大多数涉及decimal
(货币等)的情况下,取根是没有用的; 并且root将没有像您期望的decimal
所具有的预期精度。 你当然可以通过强制转换强制它(假设我们没有处理decimal
范围的极端):
decimal root = (decimal)Math.Sqrt((double)myVariableHere);
这迫使你至少承认固有的四舍五入问题。
我不明白为什么这个问题的所有答案都是一样的。
有几种方法可以从数字中计算平方根。 其中一个是艾萨克·牛顿提出的。 我只会写一个这个方法最简单的实现。 我用它来提高双平方根的准确性。
// 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且number为decimal.MaxValue),循环重复次数少于三次。
如果您想了解更多信息,请阅读(由Henry S. Warren,Jr。 撰写的Hacker’s Delight )
我刚刚遇到了这个问题,我建议使用与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); }
它不需要使用现有的Sqrt
函数,因此避免转换为double
和back,伴随着精度的损失。
简单:将您的decimal
转换为double
并调用该函数,获取结果并将其转换回decimal
。 这可能会比您自己制作的任何sqrt
function更快,并且节省了大量精力。
Math.Sqrt((double)myVariableHere);
会给你一个双倍,即你的decimal
myVariableHere
。
上述就是C#学习教程:在C#中对十进制数据类型执行数学运算?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1013213.html