j3-fortran / fortran_proposals

Proposals for the Fortran Standard Committee
175 stars 14 forks source link

A simpler sign function #246

Open rikardn opened 2 years ago

rikardn commented 2 years ago

The current SIGN function is called the "sign transfer function" and takes two arguments making it a bit surprising. A plain one argument SIGN-function for all numeric types would be a nice addition.

certik commented 2 years ago

Indeed, it is confusing to me also. I would expect a function that you call just like sign(x).

jacobwilliams commented 2 years ago

I always have to look up what the two argument are. And then also empirically figure out what it's going to do with 0.

certik commented 2 years ago

Exactly, in fact I don't remember right now which ways the arguments to sign go. I have to look it up every single time.

klausler commented 2 years ago

What would a one-argument SIGN function compute? (If it's -1, 0, or 1, then Fortran already has that. Oops, no, it doesn't, I confused it with "signum" in Haskell)

rikardn commented 2 years ago

As far as I can read in "Modern Fortran explained" by Metcalf et al. the only function named SIGN is the sign(a, b). The proposal would be to have a one argument version sign(a) that would return -1, 0 or 1 for all numeric a. I see that the current sign doesn't return 0, but instead give a positive sign for 0.

I found the rationale for the sign(a, b). It is required by the IEEE 754 floating point standard to have a function sourceFormat copySign(source, source) (section 5.5.1 in IEEE Std 754-2008). This would be the current sign function in Fortran. This also explains why 0.0 would be positive since this number has the sign bit set to 0 in the IEEE 754 representation. Potentially -0.0 would give the opposite sign. With this background perhaps the proposed one argument sign would add to the confusion.

klausler commented 2 years ago

That's the "signum" function of mathematics (and Haskell). I was wrong when I said it was in Fortran -- the standard has a "signum" function, but it's in a code example.

gklimowicz commented 2 years ago

Maybe we should add signum. Too late for 202x, but 202y...

Or would there be any issue with having the second argument to "sign" become optional?

klausler commented 2 years ago

Maybe we should add signum. Too late for 202x, but 202y...

Or would there be any issue with having the second argument to "sign" become optional?

Having the same name mean two completely different things based on the argument count? Yes, that's an issue.

klausler commented 2 years ago

Another "issue": if the second (B=) argument to SIGN were made optional, one wouldn't necessarily know at compilation time whether the intrinsic was meant to be a sign transfer or a signum until run time if the actual argument were an optional dummy argument being forwarded, a pointer, or an allocatable.

johnwcowan commented 1 year ago

Eventually deprecate SIGN and go to SIGNUM and COPYSIGN.