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.

4

3 回答 3

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.

于 2015-12-18T09:18:01.510 回答
2

Use Math.pow like this

function jumpCalc(x) {
    return (-0.004*(Math.pow(x,2))+4*x)/1000;
}
于 2015-12-18T09:22:23.297 回答
0

You can reduce this formula further to

function getThatFunc(x){
    return x * (-0.004 * x + 4) / 1000;
} 
于 2015-12-18T09:30:46.353 回答