F# Floating point ranges are experimental and may be deprecated

后端 未结 6 1791
猫巷女王i
猫巷女王i 2020-12-19 15:27

I\'m trying to make a little function to interpolate between two values with a given increment.

[ 1.0 .. 0.5 .. 20.0 ]

The compiler tells m

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-19 16:05

    As Jon and others pointed out, floating point range expressions are not numerically robust. For example [0.0 .. 0.1 .. 0.3] equals [0.0 .. 0.1 .. 0.2]. Using Decimal or Int Types in the range expression is probably better.

    For floats I use this function, it first increases the total range 3 times by the smallest float step. I am not sure if this algorithm is very robust now. But it is good enough for me to insure that the stop value is included in the Seq:

    let floatrange start step stop =
        if step = 0.0 then  failwith "stepsize cannot be zero"
        let range = stop - start 
                    |> BitConverter.DoubleToInt64Bits 
                    |> (+) 3L 
                    |> BitConverter.Int64BitsToDouble
        let steps = range/step
        if steps < 0.0 then failwith "stop value cannot be reached"
        let rec frange (start, i, steps) =
            seq { if i <= steps then 
                    yield start + i*step
                    yield! frange (start, (i + 1.0), steps) }
        frange (start, 0.0, steps)
    

提交回复
热议问题