Search code examples
javascriptmathquadratic-curve

Transport Mathematic function into a program


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.


Solution

  • ^ 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.