Std::num::Float trait: usage, "clamp" method


#1

How are functions in the Float trait intended to be used? 2.0.ln(), or Float::ln(2.0)?

I would like to be able to do something like

use std::num::max;

then write max(a,b) (like with std::cmp::max). Are there plans to add free functions as wrappers around the methods defined in Float?

Second question: would there be interest in adding a clamp(x, lb, ub) method (essentially just min(max(x, lb), ub))? There are quite a number of times I’ve wanted this for floats.


#2

What should the semantics on clamping NaN be?


#3

NaN. Otherwise you’re silently squelching errors.

There are cases where silent squelching of errors is pretty-much impossible to avoid (if rand_01() < p {...}), but in other cases NaNs should propegate.


#4

Well, clamp sounds like you can guarantee that the value is in the specified interval afterwards, so this seems like a gotcha.


#5

And you might naively think floats are ordered, but they’re not always. Seems like a reasonable compromise to me.


#6

max doesn’t return NaN unless both arguments are NaN.


#7

How weird. I just checked the IEEE754 standard and it quite clearly states the behaviour you describe for min/max (but also that all other operations receiving one or more NaNs as inputs and emitting a floating-point number should return one of the received NaNs).

Any idea why?

Interestingly, Python gets this wrong:

>>> min(1e1000-1e1000, 5)
nan