1

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Marcelo Melo
  • 421
  • 4
  • 9

1 Answers1

5

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.

Community
  • 1
  • 1
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • 3
    Note that Python changed the definition of int / int division in version 3.0. If you're still using 2.x, I would highly recommend `from __future__ import division`. – dan04 Mar 23 '17 at 22:39
  • @dan04 changed how? :) – Andy Turner Mar 23 '17 at 22:43
  • 2
    Now it returns a `float` that approximates the exact rational quotient. – dan04 Mar 23 '17 at 22:44
  • 1/10000 is not zero; it's 1.e-4. The value of exp(-1.e-4) is 0.99990. – duffymo Mar 23 '17 at 23:50
  • @duffymo In Java, `1/10000` *is* zero, because it's the division of two integer (literals). – Andy Turner Mar 24 '17 at 00:18
  • Yes, but that's not what he did in Java. Those are two doubles. Java gave the correct answer. What I'm pointing out is how the exponential function acts, regardless of computer language. Keep up. – duffymo Mar 24 '17 at 00:19
  • @duffymo I never said it did. I was making the point that `-1/10000` in python is not the same as `-1/10000` in Java, had he used ints. Don't worry, I'm keeping up. – Andy Turner Mar 24 '17 at 00:20
  • I think it's related to this: http://stackoverflow.com/questions/19517868/integer-division-by-negative-number. With this and with the fact that the numbers are integers and not float. By using Guava `Math.exp(LongMath.divide(-td, window), RoundingMode.FLOOR))` I get the same result as Python given `td` and `window` are long. – Marcelo Melo Mar 24 '17 at 00:30
  • You don't need Guava to do this calculation properly. – duffymo Mar 24 '17 at 09:58