Marcelo Melo
Marcelo Melo

Reputation: 411

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

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. What am I doing wrong?

Upvotes: 1

Views: 685

Answers (1)

Andy Turner
Andy Turner

Reputation: 140319

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 doubles, 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.

Upvotes: 5

Related Questions