in reply to strange arithmetic

I haven't found a direct answer for this (yet), (see Update below) but it's interesting that if you assign the math to another variable first, then print that variable, the number is printed correctly; for example:

$i = 2; $j = (1-1/2000)**$i; print $j;

The output is:

0.99900025

It seems that the print function is interpreting the number differently due to the parens. If you input a similar math problem directly into print, but without parens, the number comes out right.

$i = 2; print 0.9995**$i;

Output:

0.99900025

Update: print is only printing what is in the parens because it is treating that part like the complete input to a function, ignoring the exponent part. Adding the blank string in front changes print to list operator mode, printing the entire answer.

To summarize: the two modes of print are:

# function mode print (your code here);

And

# list mode print arg1, arg2, etc; # and/or the . operator
--Nick

Replies are listed 'Best First'.
Re^2: strange arithmetic
by AnomalousMonk (Archbishop) on Jan 09, 2015 at 21:23 UTC
    ... print is only printing what is in the parens because it is treating that part like the complete input to a function ...

    Deparsing with full parenthesization (see O, B::Deparse) shows this clearly. (Note, in addition to "print (...) interpreted as function...", the warning about the return value of print being raised to an exponent and then thrown away!)

    c:\@Work\Perl\monks>perl -wMstrict -MO=Deparse,-p -le "my $i = 5; print (1-1/2000)**$i; print '' . (1-1/2000)**$i; " print (...) interpreted as function at -e line 1. Useless use of exponentiation (**) in void context at -e line 1. BEGIN { $^W = 1; } BEGIN { $/ = "\n"; $\ = "\n"; } use strict 'refs'; (my $i = 5); (print(0.9995) ** $i); print(('' . (0.9995 ** $i))); -e syntax OK c:\@Work\Perl\monks>perl -wMstrict -le "my $i = 5; print (1-1/2000)**$i; print '' . (1-1/2000)**$i; " print (...) interpreted as function at -e line 1. Useless use of exponentiation (**) in void context at -e line 1. 0.9995 0.997502498750313


    Give a man a fish:  <%-(-(-(-<