Processing.js vs. Application cos/sin producing different values?

edited October 2014 in JavaScript Mode

I've been trying to port a sketch over from processing application to processing.js. Everything is being drawn at inccorect positions. And I've found that when I run cos(radians(theta)) or sin(radians(theta)) in the two different programs I get different results for the same value of theta. Is this a known issue? Is there a way to get around it?

Answers

  • Answer ✓

    The difference is because by default Processing uses the float data type and JS mode uses the double data type.

    Although it would be possible to change the data type float to double the Processing sin and cos method expect a float so would not work unless you used Math.sin and Math.cos instead, but then it wouldn't work in JavaScript mode.

    Is there a way to get around it?

    The short answer is no if you want the code to run in both Java and JavaScript mode, but the actual difference in values is minute and MOST unlikely to cause any noticeable differences between the 2 modes.

  • edited October 2014 Answer ✓

    As @quark said: Use Math.cos(), Math.sin(), etc. in order to get near results from both Java & JS Modes! =:)
    Be careful though that Java Mode is hostile to double datatype! :|
    Also, you're gonna need to suffix all literal fractional values w/ d, like: .5d, 3.1416d, 1e3d, etc.! (~~)

  • Answer ✓

    You could also try something like floor(cos(angle)*100000)*.00001 which should truncate to less decimal precision and be the same in both programs.

  • edited October 2014 Answer ✓

    Gr8 idea @rbrauer! How about scientific notation too? *-:)


    "Java Mode":

    float ang = QUARTER_PI;
    println(cos(ang));                  // 0.70710677
    println(floor(cos(ang)*1e5)*1e-5);  // 0.7071
    

    "Transpiled JS Mode":

    (function($p) {
      var ang = $p.QUARTER_PI;
      $p.println($p.cos(ang));                    // 0.7071067811865476
      $p.println($p.floor($p.cos(ang)*1e5)*1e-5); // 0.7071000000000001
    })
    

    "Regular Java":

    double ang = Math.PI/4d;
    System.out.println(Math.cos(ang));                         // 0.7071067811865476
    System.out.println(Math.floor(Math.cos(ang)*1e5d)*1e-5d);  // 0.7071000000000001
    

    "Regular JS":

    const ang = Math.PI/4.0;
    console.log(Math.cos(ang));                 // 0.7071067811865476
    console.log((Math.cos(ang)*1e5 | 0)*1e-5);  // 0.7071000000000001
    

    P.S.: About time to find an avatar for yourself, @rbrauer! <):)

Sign In or Register to comment.