I am new to C# and programing, for my first project I wanted to recreate the Math.Pow() function. My program works fine for int. Decimals I had to create a function to convert the decimal to fraction and had to write a squareroot function. However, the problem I am facing is if the fraction doesn't reduce to a smaller number then double is no longer able to handle it and program crashes. I can't use BigInteger because it doesn't support decimal values and there is no BigDecimal in C# as far as I am aware. I looked online for libraries for BigDecimal but they don't support multiplication. I am just wondering how would you handle large decimal values. FOR EXAMPLE 50 ^ 4.359 simplifies to 4359/1000 therefore, (50^(1/1000))^4359 this crashes the program. My 3 functions:
static double Exponent(double baseNum, double power)
{
double squared = 1;
int n = (int)power;
if (power == 0)
{
return squared;
}
else if (power == 1)
{
return baseNum;
}
else if (power % 2 == 0)
{
return Exponent(baseNum * baseNum, power / 2);
}
else if (power % 2 == 1)
{
return baseNum * Exponent(baseNum * baseNum, (power - 1) / 2);
}
return squared;
}
static double SquareRoot(double baseNum, double power)
{
// Assigns a random guess for the root.
double root = 2;
//The Newton Method for Computing Square Roots
while (true)
{
root = root + (baseNum - Exponent(root, power)) / (power * Exponent(root, power - 1));
if (Math.Round(Exponent(root, power), 6) == Math.Round(baseNum, 6)) break;
}
return root;
}
static double[] DecimalToFraction(double decimalValue)
{
// Converting decimal to fractions.
double[] fraction = new double[2];
// Assigns zi to decimal value.
double zi = decimalValue;
// Assigns Denominator value to zero this will be the previous value.
double d0 = 0.0;
// Assigns Denominator value to one this will be the current value.
double di = 1.0;
// Calculates the new Denominator value via the formula.
double dCurr = 1.0;
// Numerator value initialized to zero to start.
double ni = 0.0;
// The accuracy required.
double accuracyFactor = 0.000001;
int count = 0;
// Run loop until 15 iterations are reached or the accuracyFactor is reached.
while(count < 15)
{
// Formula to get the current Z value.
zi = 1 / (zi - (int)zi);
// Formula to get the new Denominator Value.
dCurr = di * (int)zi + d0;
// Formula to get the new Numerator Value.
ni = Math.Round(decimalValue * dCurr);
// Assign current denominator to old denominator.
d0 = di;
// Assign new denominator to current denominator.
di = dCurr;
count++;
// Breaks function once accuracy is reached.
if(Math.Abs(decimalValue - fraction[0]/fraction[1]) < accuracyFactor)
{
break;
}
// Assign numerator value ni to fraction[0] and current denominator di to fraction[1]
fraction[0] = ni;
fraction[1] = di;
}
return fraction;
}