Barry
Barry

Reputation: 13

Math.exp not working as expected in Javascript

I'm trying to make this formula work in javascript:

99 * exp(-0.0065 * (28 - variable)2)

I need the number returned to be an integer. This is what I have:

Math.round(99*(Math.exp(-0.0065*((28-variable)^2))))

If the variable were 28, I would expect a result of 99, but I get 98. When the variable is 18 I would expect 52; I get 94. When variable is 8, I expect 7 but get 86.

My variable will only ever be an integer ranging from -2 to 28.

I probably have the brackets in the wrong place or something, but I just can't see what I have done wrong.

Upvotes: 1

Views: 359

Answers (4)

user9335261
user9335261

Reputation:

^ is used for XOR operations, you need to use Math.pow instead

Math.round(99*(Math.exp(-0.0065*(Math.pow((28-variable),2)))))

Upvotes: 0

mustachioed
mustachioed

Reputation: 533

Math.round(99 * Math.exp(-0.0065 * Math.pow(28-variable, 2)))

Try this instead. ^ is a bitwise XOR. Math.pow is the function you are seeking.

Upvotes: 1

user9335231
user9335231

Reputation:

Use Math.pow instead of ^

Math.round(99 * Math.exp(-0.0065 * Math.pow(28 - variable, 2)))

For more infos expressions and operators, check this link

Upvotes: 0

Damon
Damon

Reputation: 4336

^ in javascript is the bitwise XOR operator, not an exponent.

You are looking for Math.pow or ** (ES7 - use the former for browsers):

Math.round(99 * Math.exp(-0.0065 * (28-variable) ** 2))

Now let's pull that into a function and test it with your expected outputs:

const fn = n =>
  Math.round(99 * Math.exp(-0.0065 * (28-n) ** 2))

console.log(fn(28))
console.log(fn(18))

Upvotes: 3

Related Questions