Извлечь квадратный корень из числа типа decimal - C#
Формулировка задачи:
Возникла необходимость работать с типом decimal. Но sqrt вот с ним не работает. Не подскажете, как извлечь квадратный корень в числа такого типа?
Решение задачи: «Извлечь квадратный корень из числа типа decimal»
textual
Листинг программы
// 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;
}