I'm trying to implement this curve as part of the leveling system of a small game I'm currently working on. The equation is as follows
f(x) = -e^-((-log(7)/100)*(100-x))+7
Which in python can be defined as
f=lambda x:-e**-((-log(7)/100.0)*(100-x))+7
Running this function in the Python console returns the values expected. I ported it over to Java, where it takes the form of:
public static double f(float x) {
return (Math.pow(-Math.E, -((-Math.log(7)/100)*(100-x)))+7);
}
However, mysteriously, this always returns NaN
. I've never encountered this problem before, what is going on?
(Putting my comment as the answer)
The expressions are not the same. In python it looks like -(e**someNum)
. In java it looks like (-e)**someNum
.
Think about it (in a pretty raw fashion), what would you get when you mutliply a negative number some irrational number of times. Thats why you get a NaN.
What you want in Java is this:
public static double f(float x) {
return 7 - Math.pow(Math.E, -((-Math.log(7)/100)*(100-x)));
}
See Math#pow
:
If the first argument is finite and less than zero then if the second argument is finite and not an integer, then the result is NaN.
And in your case.. that's the case.
Always look at the docs, they save you a lot of time.
The reason for this is that if you do any negative number to the power of a non-integer, you are taking the root of it somewhere along the lines. For example, -e ^ .5 is the same as the square root of -e, and -e ^ 1.5 is the same as the square root of -e, cubed.
Really, you need to edit your real-world idea of the function:
f(x) = -e^-((-log(7)/100)*(100-x))+7
because it's actually:
f(x) = -(e^-((-log(7)/100)*(100-x)))+7
Remember that unary operators take precedence over even exponents: -e is evaluated before e^x.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With