Decimal sort

M

mdudley

Is there any way to sort floating point numbers in perl? Every
example I have tried has failed. Numerical sort appears to NOT to be
a numerical sort but rather an integer sort.

Thanks,

Marshall
 
J

John W. Krahn

mdudley said:
Is there any way to sort floating point numbers in perl? Every
example I have tried has failed. Numerical sort appears to NOT to be
a numerical sort but rather an integer sort.

Perhaps you are sorting them as strings instead of numbers?



John
 
S

Steve C

mdudley said:
Is there any way to sort floating point numbers in perl? Every
example I have tried has failed. Numerical sort appears to NOT to be
a numerical sort but rather an integer sort.

worksforme
perl -e 'print join ("\n", sort ( 0.1, 0.7, 0.3, 0.25, 0.5))'
0.1
0.25
0.3
0.5
0.7
 
J

Jürgen Exner

mdudley said:
Is there any way to sort floating point numbers in perl? Every
example I have tried has failed. Numerical sort appears to NOT to be
a numerical sort but rather an integer sort.

Please post a minimal working sample program including sampe data as
needed that demonstrates your problem. Because every example that I have
tried has worked just fine.

jue
 
S

Steve C

Oops. Forgot about default sort function being string cmp. Although that
tends to work in a surprising number of cases.

perl -e 'print join ("\n", sort {$a <=> $b} (0.1, 0.7, -0.3, 0.25, 0.5))'
-0.3
0.1
0.25
0.5
0.7
 
J

John Bokma

Steve C said:
worksforme
perl -e 'print join ("\n", sort ( 0.1, 0.7, 0.3, 0.25, 0.5))'
0.1
0.25
0.3
0.5
0.7

Coincidence. That's why you must read documentation...

perl -e 'print join("\n", sort ( 0.0001, 0.000002, 0.1 ))'
0.0001
0.1
2e-06


Note that sort defaults to string compare:

perl -e 'print join("\n", sort { $a <=> $b } ( 0.0001, 0.000002, 0.1 ))'
2e-06
0.0001
0.1
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top