1

I try to import a mathematic function into Javascript. It's the following formula: http://www.wolframalpha.com/input/?i=-0.000004x%5E2%2B0.004x

Example Values:

f(0) = 0

f(500) = 1

f(1000) = 0

So that is my function:

function jumpCalc(x) {
    return (-0.004*(x^2)+4*x)/1000;
}

The values are completely wrong.

Where is my mistake? Thanks.

Community
  • 1
  • 1
Standard
  • 1,450
  • 17
  • 35
  • 4
    x^2 does not mean x power 2 in javascript, it's the xor operator. There is not power operator in JS, so try changing this to x * x. – Daniel Perez Dec 18 '15 at 09:17

3 Answers3

7

^ isn't doing what you think it is. In JavaScript, ^ is the Bitwise XOR operator.

^ (Bitwise XOR)

Performs the XOR operation on each pair of bits. a XOR b yields 1 if a and b are different.
MDN's Bitwise XOR documentation

Instead you need to use JavaScript's inbuilt Math.pow() function:

Math.pow()

The Math.pow() function returns the base to the exponent power, that is, baseexponent.
MDN's Math.pow() Documentation

return (-0.004*(Math.pow(x, 2))+4*x)/1000;

Working JSFiddle.

Community
  • 1
  • 1
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
2

Use Math.pow like this

function jumpCalc(x) {
    return (-0.004*(Math.pow(x,2))+4*x)/1000;
}
0

You can reduce this formula further to

function getThatFunc(x){
    return x * (-0.004 * x + 4) / 1000;
}