Search code examples
javascriptpython-3.xexponent

Are my Javascript and Python code giving me different answers because of exponents, or something else?


I've ported a simple algorithm over from Python3 to Javascript, and surprisingly, I'm getting different answers. The Python code works as expected, and I don't know why the Javascript acts differently.

Here's the Python:

def foo():
    theArray = [1,2,3,4,5,6]
    a = theArray[0]
    b = theArray[1]
    c = theArray[2]
    d = theArray[3]
    e = theArray[4]
    f = theArray[5]
    res = (((a**2 + b**2 - (d - e)^3 + (b//e)^2)/ ((a**2 + b**2 - (d - e)^3) + c**2 + (f-4)^2 + (c//d)^2))*0.75)
    return res

Python3 Result: 0.32..

Here's the Javascript code:

function foo() {
    theArray = [1,2,3,4,5,6]
    var a, b, c, d, e, f
    a = theArray[0]
    b = theArray[1]
    c = theArray[2]
    d = theArray[3]
    e = theArray[4]
    f = theArray[5]
    res = (((a**2 + b**2 - (d - e)**3 + (b/e)**2)/ ((a**2 + b**2 - (d - e)**3) + c**2 + (f-4)**2 + (c/d)^2))*0.75)
    return res
}

Javascript Result: 0.27..

Using Math.pow() in the Javascript code didn't change anything.


Solution

  • Note that they are not the same formulas.

    In your python code you have:

    res = (((a**2 + b**2 - (d - e)^3 + (b//e)^2) / ((a**2 + b**2 - (d - e)^3) + c**2 + (f-4)^2 + (c//d)^2))*0.75
    

    Which has (d - e)^3 and (b//e)^2 and (f-4)^2

    In your js code you have:

    res = (((a**2 + b**2 - (d - e)**3 + (b/e)**2) / ((a**2 + b**2 - (d - e)**3) + c**2 + (f-4)**2 + (c/d)^2))*0.75)
    

    Which instead has (d - e)**3 and (b//e)**2 and (f-4)**2

    The XOR operation is a very different operation from exponents.

    Also, do note that in python you have lots of integer divides. In javascript the equivalent would be something like:

    (Math.floor(b/e))^2
    

    So the correct js formula should be:

    res = (((a**2 + b**2 - (d - e)^3 + Math.floor(b/e)^2) / ((a**2 + b**2 - (d - e)^3) + c**2 + (f-4)^2 + Math.floor(c/d)^2))*0.75