Marcelo Melo -4 years ago 139
Java Question

# Java Math.exp() and Python math.exp()

So, I don't know much about Python, but the following snippet result is

`0.367879441171`

``````from math import exp

window = 10000
td = 1

print exp(-td/window)
``````

Whereas in Java the snippet below results in
`0.9999000049998333`

``````import java.time.Clock;
import java.time.Duration;
import java.time.Instant;

public class HelloWorld{
public static void main(String []args){
double td = 1d;
double window = 10000d;

System.out.println(Math.exp(- td / window));
}
}
``````

I could swear these are equivalent but they're apparently not. Can someone explain me what I'm doing wrong?

Python code: http://www.tutorialspoint.com/execute_python_online.php?PID=0Bw_CjBb95KQMcXRkLUdXbHdBSEU

JavaCode: http://www.tutorialspoint.com/compile_java8_online.php?PID=0Bw_CjBb95KQMeEZZZFJLdERMb0k

The python example is doing integer division:

``````print -td/window
``````

shows `-1`. Note that this is different to if you had written the equivalent in Java, using `int` variables, since `-1/10000` is zero:

``````int window = 10000;
int td = 1;
System.out.println(-td/window);
``````

shows `0`.

The Python behavior surprises me, as I've never noticed that Python always rounds down, not that I've ever looked though!

But you've not done exactly the same in Java, you've divided two `double`s, meaning you're doing floating point division.

In python, try casting `td` to a float:

``````print -float(td)/window
``````

shows `-0.0001`, which is akin to Java, where you're using `double`.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download