in reply to Re^5: Weird behavior of int()
in thread Weird behavior of int()
I feel like 'int' ought to have a stronger contract of doing what's written on the label. If it can't convert to an int, it ought to return undef or 0, not just ignore the attempt
int doesn't contract to return an IV; it contracts to return the integer portion of the expression given. An infinitely large floating point would convert to an infinitely large integer, so infinity is still the logical conclusion (IMO).
In my mind, perl's int is equivalent to c's math.h:'trunc', not the int typecast in c.
output:#include <math.h> #include <stdio.h> int main() { double x; x = 3.14; printf("trunc(%f) = %f\n", x, trunc(x)); x = -2.718; printf("trunc(%f) = %f\n", x, trunc(x)); x = +INFINITY; printf("trunc(%f) = %f\n", x, trunc(x)); x = -INFINITY; printf("trunc(%f) = %f\n", x, trunc(x)); x = +NAN; printf("trunc(%f) = %f\n", x, trunc(x)); x = -NAN; printf("trunc(%f) = %f\n", x, trunc(x)); }
trunc(3.140000) = 3.000000 trunc(-2.718000) = -2.000000 trunc(inf) = inf trunc(-inf) = -inf trunc(nan) = nan trunc(nan) = nan
The docs for int could be improved to say what it does on those edge cases (the trunc docs that I linked do explicitly define those behaviors), but I personally think that int returns the right thing for those inputs, and for me, it is the Answer of Least Astonishment.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^7: Weird behavior of int()
by ikegami (Patriarch) on May 21, 2024 at 23:11 UTC | |
by pryrt (Abbot) on May 21, 2024 at 23:38 UTC | |
by ikegami (Patriarch) on May 22, 2024 at 14:12 UTC | |
by pryrt (Abbot) on May 22, 2024 at 17:10 UTC |