[erlang-questions] Strange float / tuple problem

zxq9 zxq9@REDACTED
Sun Jun 5 06:25:02 CEST 2016


On 2016年6月5日 日曜日 13:11:30 zxq9 wrote:
> On 2016年6月4日 土曜日 10:07:11 Donald Steven wrote:
> > Thanks Matthias and Craig.  I see the issue and I've got a work around.  
> > BTW, is there a way to truncate a float to a given # of places, not just 
> > 0 -- not just a formatted output, but a true truncation?
> 
> approximate(Precision) ->
>     fun(Z, Z) -> true;
>        (Z, Q) -> (Z - Precision =< Q) and (Q =< Z + Precision)
>     end.

I forgot to mention something... in your particular case you may really
be wanting to convert to a specific value instead of just compare, in that
case a small change is more direct:

force_fit(Precision) ->
    Approx = approximate(Precision),
    fun(Z, Q) ->
        case Approx(Z, Q) of
            true  -> Z;
            false -> Q
        end
    end.

1> Rough = numbers:force_fit(0.00001).
#Fun<numbers.1.117927507>
2> Rough(0.0, 4.440892098500626e-16).
0.0
3> Rough(0.0, 0.1).
0.1

Obviously this would be playing with fire on intermediate values (*much*
more dangerous than the usual caveats that apply to iterative processing
with floats). But it may be closer to the behavior you are looking for --
conceptually, anyway. I have no idea what you're really doing.

-Craig



More information about the erlang-questions mailing list