0

How can I calculate 98 raised to the power of exp(13-5) using JavaScript?

Is this the way?

Math.pow(98,Math.exp(8))
Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
fn79
  • 303
  • 6
  • 18
  • Have you tried it? When I run it [here on jsFiddle](http://jsfiddle.net/bTuhE/) it returns "_Infinity_". – jahroy Apr 12 '13 at 01:49
  • If you're trying to raise 98 to the exponent of the Euler's constant to the 8th, then yes. But, that's probably going to give you "Infinity" in most JS environments. ;) – ryanbrill Apr 12 '13 at 01:54
  • 4
    Yep... Now that I see what _Math.exp_ is, you're trying to raise 98 to the "_almost 3,000th power_".... so you're talking about a number that's pretty huge. So... You're performing the math correctly, but JavaScript's number system is not able to represent the result as a number. Check out [this answer](http://stackoverflow.com/a/307200/778118) for some info about the largest number JavaScript can represent. – jahroy Apr 12 '13 at 01:55
  • Thanks for your replies. I think I am not getting the numbers right, which are again derived from different formulas. I will check and post back here – fn79 Apr 12 '13 at 02:01
  • another question I have is...is ln(x) same as Math.log(x)? – fn79 Apr 12 '13 at 02:44

1 Answers1

0

When I need to handle large positive numbers that would overflow standard floating point types then I store the numbers as log of the number instead. So instead of calculating 98 to the power of exp(8), I'd calculate exp(8) * log(98) and work with that. I haven't (yet) come across a situation where even that method was inadequate to store the numbers that I needed. However, I have come across several situations where the right answer involves multiplying very very large numbers by very very small numbers, and in that situation using logs as I described has avoided overflows/underflows which would result in the wrong answer.

Update: I suspect this is some kind of homework question relating to how to get round the problem that 98 ^ exp(8) is too big for standard floating point types. In which case, I think my suggestion to use logs comes in handy. For example, to print out the number in C# you could do the following:

double x = Math.Exp(13 - 5) * Math.Log(98);  // the number required is exp(x)
int exponent = (int)Math.Floor(x / Math.Log(10));
double absissae = Math.Exp(x - exponent * Math.Log(10));
System.Diagnostics.Trace.WriteLine(absissae.ToString() + " E " + exponent.ToString());

which produces the output

5.77130918514205 E 5935
Stochastically
  • 7,616
  • 5
  • 30
  • 58