No such thing as a small change PerlMonks

### Wrong calculations in for loop

 on Aug 22, 2012 at 12:55 UTC Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I want to create a simple output ranging from 0 to zmax in distinct steps. Those steps shall get larger towards the end. Here's my simple script:
```my \$zmax = 60;    # Maximum depth in your model
my \$dz = 0.05;    # Grid spacing in z-direction

for (my \$i=0; \$i <= \$zmax; \$i = \$i+\$dz) {
print \$i."\n";
}
And here's the output at a later stage:
```3.6
3.65
3.69999999999999
3.74999999999999
That's not the correct value !! This prevents me from making a direct comparison with an integer number (which I can find ways around), but the result is simply wrong!! What's happening there?

Replies are listed 'Best First'.
Re: Wrong calculations in for loop
by toolic (Bishop) on Aug 22, 2012 at 13:02 UTC
Re: Wrong calculations in for loop
by MidLifeXis (Monsignor) on Aug 22, 2012 at 13:01 UTC
Re: Wrong calculations in for loop
by BrowserUk (Pope) on Aug 22, 2012 at 13:50 UTC

Simple solution:

```for( my \$i = 0; \$i < 6000; \$i += 5 ) {
say \$i / 100
};;
0
0.05
0.1
0.15
0.2
0.25
0.3
0.35
0.4
0.45
0.5
0.55
0.6
0.65
...
3.5
3.55
3.6
3.65
3.7
3.75
3.8
3.85
3.9
3.95
4
...

With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

The start of some sanity?

Re: Wrong calculations in for loop
by moritz (Cardinal) on Aug 22, 2012 at 13:10 UTC

Luckily you can run the script with only very small changes under Perl 6, and it produces the output you expect:

```use v6;
my \$zmax = 60;    # Maximum depth in your model
my \$dz = 0.05;    # Grid spacing in z-direction

loop (my \$i=0; \$i <= \$zmax; \$i = \$i+\$dz) {
say \$i;
}

produces

```...
3.6
3.65
3.7
3.75
...
59.9
59.95
60

It accomplishes that magic by doing math with rationals (stored as integer numerator and denominator) by default.

OK, but getting the same result in Perl 5 is almost as easy:

```#! perl
use strict;
use warnings;

my \$zmax = 60;      # Maximum depth in your model
my \$dz   =  0.05;   # Grid spacing in z-direction

print +(\$_ * \$dz), "\n" for (0 .. int((\$zmax / 0.05) + 0.5));

:-)

Athanasius <°(((><contra mundum

Or even simpler, just change the print to printf

```my \$zmax = 60;    # Maximum depth in your model
my \$dz = 0.05;    # Grid spacing in z-direction

for (my \$i=0; \$i <= \$zmax; \$i = \$i+\$dz) {
printf("%.2f\n", \$i);
}

Re: Wrong calculations in for loop
by Anonymous Monk on Aug 22, 2012 at 13:08 UTC

Create A New User
Node Status?
node history
Node Type: perlquestion [id://989020]
Approved by Perlbotics
help
Chatterbox?
 [Corion]: ambrus: Yes but I also need to implement the file / IO watcher, because Prima has that (in Prima::File), and I need to supply the appropriate thing to make push_write etc. work with Prima [ambrus]: Corion: yes, you need to implement the io watcher, which should be simple because Prima::File is basically that, and the timer watcher form Prima::Timer [Corion]: ... or so I think. As I said, I'm somewhat vague on how to make AnyEvent cooperate with a callback-driven IO event loop that gives me callbacks when data is available or can be written [ambrus]: what push_write thing? I don't think you need that. that's implemented generically by AnyEvent::Handle [Corion]: ambrus: Yeah, that's what I think as well. But you give me an idea, maybe I should start with implementing the timer, as that should be far simpler and with fewer edge-cases/nasty interaction than the file watcher [ambrus]: You only provide the watcher part that tells when the handle is readable or writable, not the actual writing and reading. [Corion]: ambrus: Hmmm. It makes sense that AnyEvent would implement the push_write itself, but I think I don't have a good idea of where the boundary between AnyEvent and the underlying event system lies... Implementing the timer should give me a better idea [ambrus]: Corion: push_write is in the higher level abstraction of AnyEvent::Handle, not in the watcher [Corion]: ambrus: Hmm - rereading Prima::File, that merrily coincides with what Prima does - it tells you "you can read", and you're supposed to read from the fh yourself. I thought it called you with the data already read, which would've been harder to integrate [ambrus]: you just need an io watcher, created by &AnyEvent::Impl:: Whatever::io(...)

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (8)
As of 2016-12-08 12:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
On a regular basis, I'm most likely to spy upon:

Results (141 votes). Check out past polls.