I just want to let you know: this is a repeat of a question Ive already asked, but was closed down. I really want an answer to this but I dont have the patience to wait until they reopen the question since its already been closed for quite some time.
I’m supposed to write a calculator in C# and I’ve done most of the things, but I’m not sure how to write a root method.
I’ve looked around, but I’m just not able to translate some of the things online into proper C# code.
Since this was closed due to inaccuracy: I cant use Sqrt since I’m supposed to do it myself. I’ve already written things for all the other operators and now I want to be able to do a a^(b/c) which is just root^c(a^b). I’ve done all the separation and now I have
public double RootMethod(double rootExponent, double number)
{
double result = 1;
//calculate result
return result;
}
Whilst I do have my own actual number classes with operator methods, I only want a "normal" example" since I think I’ll be able to translate to my operators. So you can even use some Math methods (as long as it’s not Sqrt) because I translated most of those. If you use one I can’t use, I’ll tell you, but for now I just really want to see some example in C#.
Also Important YES you CAN use Math.Pow in your suggestion, NO I cant use it myself, since this is what I need to write myself BUT Ive already written the POW base translation to work for my classes so I should just be able to swap that method out.
Ive looked around multiple Foroums and I know that there are way to calculate Roots without using one, but Im not able to really understand the ways Ive found, yet alone translate them to c# code.
>Solution :
public double RootMethod(double rootExponent, double number)
{
double guess = 1;
double accuracyFactor = 0.0001;
double difference = 1;
double result = 1;
double rootExponentMinusOne = rootExponent - 1;
while (difference > accuracyFactor)
{
result = ((guess * rootExponentMinusOne) + (number / (Math.Pow(guess, rootExponentMinusOne)))) / rootExponent;
difference = result - guess;
if (difference < 0)
{
difference *= -1;
}
guess = result;
}
return result;
}
I hope this is good enough for you. But be aware that this can still produce wrong results, if the accuracy Factor isnt high enough.