0

I've am writing a calculator and am trying to support taking numbers to the nth root. The problem I've encountered is that when attempting to take negative numbers to an odd root it outputs NaN when it shouldn't. The code a have written for this is:

ans = Math.Pow(Convert.ToDouble(a), (1 / Convert.ToDouble(b)));

The problem is that 1 / Convert.ToDouble(h) isn't seen as a fraction meaning that it won't allow it to be calculated. For example if a cubic is trying to be calculated that will output 0.3333333333333333, which technically isn't the same as 1/3. Just making the value positive then sticking a negative on the answer doesn't really work either as it would allow negative numbers to be taken to an even root.

How could I do this?

I think I could just check for n being even / odd but how would I do this while also allowing n to be a decimal.

  • 1
    [This comment](https://stackoverflow.com/questions/18657508/c-sharp-find-nth-root#comment74184692_18657674) may be useful. If you're doing a calculation and producing a decimal (or float/double) representation of the answer, you're going to run into problems with imperfect precision. Your calculator will encounter the same problem with simple division. The only way to avoid that is to make your calculator vastly more complicated by making it capable of representing fractions and applying all its mathematical operations using fractions. – StriplingWarrior Aug 21 '22 at 05:25

1 Answers1

0

System.Numerics.Complex.Pow should do the trick

Rezo Megrelidze
  • 2,877
  • 1
  • 26
  • 29