more useful options PerlMonks

### Re: Wrong calculations in for loop

by moritz (Cardinal)
 on Aug 22, 2012 at 13:10 UTC ( #989026=note: print w/ replies, xml ) Need Help??

in reply to Wrong calculations in for loop

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.

Comment on Re: Wrong calculations in for loop
Replies are listed 'Best First'.
Re^2: Wrong calculations in for loop
by Athanasius (Canon) on Aug 22, 2012 at 13:22 UTC

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);
}

Create A New User
Node Status?
node history
Node Type: note [id://989026]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (16)
As of 2016-05-04 14:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
What font do you use for programming?

Results (79 votes). Check out past polls.