CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
generate numbers

 



sulis
New User

Jan 14, 2005, 12:23 AM

Post #1 of 4 (421 views)
generate numbers Can't Post

i have this set of codes. I wana generate numbers to become :
0.01
0.02
0.03
0.04
0.05
0.06
0.07
0.08
0.09
0.1
0.11
0.12
0.13
0.14
0.15
0.16
0.17
0.18
0.19
0.2
0.21

But once it reached a certain number it becomes:
0.78
0.79
0.8
0.81
0.820000000000001
0.830000000000001
0.840000000000001
0.850000000000001

whats the mistake here?

Code
for ($i = 0; $i <= 10; $i=$i+0.01) { 
print "$i\n";
}


KevinR
Veteran


Jan 14, 2005, 1:32 AM

Post #2 of 4 (420 views)
Re: [sulis] generate numbers [In reply to] Can't Post

there is no "mistake", its just a symptom of the way numbers are stored in binary. use sprintf, something like this:


Code
for (my $i = 0; $i <= 10; $i=$i+0.01) {  
my $num = sprintf("%.2f", $i);
print "$num\n";
}

-------------------------------------------------


sulis
New User

Jan 14, 2005, 6:57 AM

Post #3 of 4 (414 views)
Re: [KevinR] generate numbers [In reply to] Can't Post

hey thanks! it worked.. Wink


davorg
Thaumaturge / Moderator

Jan 14, 2005, 7:42 AM

Post #4 of 4 (410 views)
Re: [sulis] generate numbers [In reply to] Can't Post

As an alternative to KevinR's (very good) solution, you can also keep the numbers as integers for as long as possible.


Code
#!/usr/bin/perl 

use strict;
use warnings;

for (my $i = 0; $i <= 1000; $i++) {
print $i/100, "\n";
}


--
Dave Cross, Perl Hacker, Trainer and Writer
http://www.dave.org.uk/
Get more help at Perl Monks

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives