Armando P. [email protected] wrote:

I actually like Maddox truncate example. Thanks Maddox. i wasnt aware

of both that feature and *.format Klemme suggested.

I’m using that :

def aprox( eps = 1.0e-10 )

( self / eps ).round * eps

end

with :

a_float = 1.2345678901234567890

epss = [ 1.0e-10, 1.0e-8, 1.0e-6, 1.0e-4, 1.0e-2, 1.0, 1.0e2]

epss.each do | eps |

puts “#{a_float}.aprox( #{eps} ) -o-> #{a_float.aprox( eps )}”

end

gives :

1.23456789012346.aprox( 1.0e-10 ) -o-> 1.2345678901

1.23456789012346.aprox( 1.0e-08 ) -o-> 1.23456789

1.23456789012346.aprox( 1.0e-06 ) -o-> 1.234568

1.23456789012346.aprox( 0.0001 ) -o-> 1.2346

1.23456789012346.aprox( 0.01 ) -o-> 1.23

1.23456789012346.aprox( 1.0 ) -o-> 1.0

1.23456789012346.aprox( 100.0 ) -o-> 0.0

I’m also using an aproximate float comparator :

def ===( aFloat, eps = 1.0e-10)

begin

clazz = aFloat.class.to_s

raise “Argument "#{aFloat}" must be a Float (being of

#{clazz}).” if clazz != “Float”

( self > aFloat - eps ) && ( self < aFloat + eps )

rescue

puts “An error occurred: #{$!}”

nil

end

end

with :

vref = 2.0

val = [ 2.00000000002, 2.00000002, 2.00002, 2.002 ]

val.each do | v |

puts “( #{vref} ===? #{v} ) = #{( vref === v )}”

puts “( #{vref} ===? #{v}, 1.0e-8 ) = #{( vref.===(v, 1.0e-8) )}”

puts “( #{vref} ===? #{v}, 1.0e-6 ) = #{( vref.===(v, 1.0e-6) )}”

puts “( #{vref} ===? #{v}, 1.0e-4 ) = #{( vref.===(v, 1.0e-4) )}”

end

gives :

( 2.0 ===? 2.00000000002 ) = true

( 2.0 ===? 2.00000000002, 1.0e-8 ) = true

( 2.0 ===? 2.00000000002, 1.0e-6 ) = true

( 2.0 ===? 2.00000000002, 1.0e-4 ) = true

( 2.0 ===? 2.00000002 ) = false

( 2.0 ===? 2.00000002, 1.0e-8 ) = false

( 2.0 ===? 2.00000002, 1.0e-6 ) = true

( 2.0 ===? 2.00000002, 1.0e-4 ) = true

( 2.0 ===? 2.00002 ) = false

( 2.0 ===? 2.00002, 1.0e-8 ) = false

( 2.0 ===? 2.00002, 1.0e-6 ) = false

( 2.0 ===? 2.00002, 1.0e-4 ) = true

( 2.0 ===? 2.002 ) = false

( 2.0 ===? 2.002, 1.0e-8 ) = false

( 2.0 ===? 2.002, 1.0e-6 ) = false

( 2.0 ===? 2.002, 1.0e-4 ) = false