Javascript floating point is getting complicated


#1

Hello,

I got inspiration from the “Animating Many Things on a Canvas” tutorial of this website and wanted to create a canvas animation of similar sorts but which looks like a single line tracing the path of the fibonacci arc.

This is the actual code i used-

function drawCircle() {
    //mainContext.clearRect(0, 0, canvasWidth, canvasHeight);
     
    // color in the background
    mainContext.fillStyle = "#EEEEEE";
    mainContext.fillRect(0, 0, canvasWidth, canvasHeight);
     
    // draw the circle
    //mainContext.beginPath();  
    xPos += radius*Math.cos(angle);
    yPos += radius*Math.sin(angle);
  
    mainContext.arc(xPos, yPos, 2, 0, Math.PI*2, true);
    mainContext.closePath();
     
    // color in the circle
    mainContext.fillStyle = "#006699";
    mainContext.fill();
  
    angle += Math.PI/128;
    //console.log(angle % (Math.PI/2) === 0);
  
    if(angle % (Math.PI/2) === 0){  // This is where i am having a problem
      radius = 2 * radius;
      console.log(radius);
    }
    
  
    requestAnimationFrame(drawCircle);
}
drawCircle();

i actually got this code by manipulating the code from ‘Creating a Simple HTML5 Canvas Animation’ tutorial… I am extremely grateful to you for that!
This code tries to multiply the radius(of the Fibonacci arc) by 2 everytime the angle becomes a multiple of Math.PI/2 but since everything is a floating point in JS that if statement always returns false and the radius remains the same. Hence instead of a fibonacci arc i just got this -


Is there any way to handle floating point manipulation.
I tried Math.floor() but that rounds off to the nearest integer and it will not be useful for this animation.
Is there any simple way to handle this? Please help.


#2

remove the Math.PI and multiply by 2

angle += 1/64
if (Number.isInteger(angle))

#3

You can also consider rounding your numbers to whatever level of precision you want: https://www.kirupa.com/html5/rounding_numbers_in_javascript.htm :slight_smile:


#4

thanks for the quick reply.
will implement this and get back


#5

Wow missed this tutorial.
will check this out.
thanks for the quick reply


#6

catches up a little with Python](https://developers.google.com/web/updates/2018/05/bigint)


#7

Indeed! It is surprising to see how long it took JavaScript to get this far on this area :stuck_out_tongue:


#8

Python automatically makes all integers as big as they need to be, JavaScript couldn’t go that route and stay compatible with older versions.