Abhishek Bhatia
Abhishek Bhatia

Reputation: 9806

NetLogo updation error approximation issue

Please check the NetLogo code below with output.

CODE:

to create-files
     let i 0.10
     while[i < 1]
     [
       set i i + .05
       show i
     ]
  end

OUTPUT:

observer: 0.15000000000000002
observer: 0.2
observer: 0.25
observer: 0.3
observer: 0.35
observer: 0.39999999999999997
observer: 0.44999999999999996
observer: 0.49999999999999994
observer: 0.5499999999999999
observer: 0.6
observer: 0.65
observer: 0.7000000000000001
observer: 0.7500000000000001
observer: 0.8000000000000002
observer: 0.8500000000000002
observer: 0.9000000000000002
observer: 0.9500000000000003
observer: 1.0000000000000002

I wonder the why is updation error? Is there some approx. taking place? How to avoid it?

Upvotes: 2

Views: 46

Answers (2)

Seth Tisue
Seth Tisue

Reputation: 30453

What Bryan said. But note also:

to create-files
  let i 2
  while [i < 20] [
    set i i + 1
    show i / 20
  ]
end

prints:

observer: 0.15
observer: 0.2
observer: 0.25
observer: 0.3
observer: 0.35
...

Upvotes: 2

Bryan Head
Bryan Head

Reputation: 12580

Take a look at the section on floating-point accuracy in the NetLogo programming guide. Virtually every widely used programming language has the same problem. Essentially in order to be able to represent both really small number and really big numbers, you get problems like this.

A simple fix is to use precision to round the numbers off to the decimal that you want. In your case, you probably want:

to create-files
     let i 0.10
     while[i < 1]
     [
       set i precision (i + .05) 2
       show i
     ]
end

Upvotes: 3

Related Questions