Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The equation -e**-((-log(7)/100.0)*(100-x))+7 returns NaN

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?

like image 597
user2963567 Avatar asked Nov 07 '13 06:11

user2963567


3 Answers

(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)));
}
like image 180
UltraInstinct Avatar answered Nov 04 '22 19:11

UltraInstinct


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.

like image 30
Maroun Avatar answered Nov 04 '22 18:11

Maroun


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.

like image 22
michaelsnowden Avatar answered Nov 04 '22 18:11

michaelsnowden