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

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.

1 Like

What should the semantics on clamping NaN be?

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.

1 Like

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

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

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

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)