Why does it happen?

Hello. Why my program doesn’t return the sequel 0.0, 0.1, 0.2, 0.3, 0.4, 0.5… and so on ??? Take a look:

var c;
function setup() {
  createCanvas(400, 400);
  c = 0;
}
function draw() {
   c += 0.1
   print(c);
}

And the numbers in console are:

  • 0.1
  • 0.2
  • 0.30000000000000004
  • 0.4
  • 0.5
  • 0.6
  • 0.7
  • 0.7999999999999999
  • 0.8999999999999999
  • 0.9999999999999999
  • 1.0999999999999999
  • 1.2

… and so on.

1 Like

I recently read about this issue in the Nyhoffs’ book “Processing: An Introduction to Programming”.
Basically they write that “computers sometimes produce inaccurate results when fractions are involved.”
They explain this is because computers do not use a decimal (base-10) system, but rather they use a binary system (base-2). If you have access to their book, see pp 61-62 for full explanation.

Or check out this explanation of conversion from decimal to binary:

And if you’re very curious, there’s a long wikipedia on the topic:

3 Likes

Of course, you do know that you can format them?

var c;

function setup() {
  frameRate(2);
  createCanvas(400, 400);
  c = 0;
}

function draw() {
  background(255);
  c += 0.1
  text(nf(c, 0, 1), 10, 10);
}
2 Likes