Code: Select all
dim a as double
dim b as single
a = 5.1
b = 5.1
print a,b
if a = 5.1 then print "a = 5.1"
if b = 5.1 then print "b = 5.1"
sleep
Code: Select all
dim a as double
dim b as single
a = 5.1
b = 5.1
print a,b
if a = 5.1 then print "a = 5.1"
if b = 5.1 then print "b = 5.1"
sleep
As Munair told you above, it's the precision of the representation what's preventing to compare them for equality. In general, you don't want to do a direct comparison against a floating-point value, but need to do an 'approximate' comparison:jaskin wrote:Can someone please explain what's going on here? I see "a = 5.1" printed but not "b = 5.1" when I run the following code.
Code: Select all
const as double EPSILON = 1e-5
#define fcomp( value1, value2 ) _
iif( abs( value1 - value2 ) < EPSILON, true, false )
dim as double _
a = 5.1
dim as single _
b = 5.1
? a, b
? "a = 5.1", fcomp( a, 5.1 )
? "b = 5.1", fcomp( b, 5.1 )
?
a = 5.10001
b = 5.10001
? "a = 5.10001", fcomp( a, 5.1 )
? "b = 5.10001", fcomp( b, 5.1 )
sleep()
Code: Select all
'' Or single, if your app can get away with it
type float as double
dim as float _
a = 5.1
b = 5.1
? a, b
? "a = 5.1", cbool( a = b )
? "b = 5.1", cbool( a = b )
sleep()
Code: Select all
dim a as double
dim b as single
a = 5.1#
b = 5.1!
print a,b
if a = 5.1# then print "a = 5.1"
if b = 5.1! then print "b = 5.1"
sleep
That only works with literals:dodicat wrote:Just tag the end of the literal to what it represents (not always double)
Code: Select all
const as double EPSILON = 1e-5
#define fcomp( value1, value2 ) _
iif( abs( value1 - value2 ) < EPSILON, true, false )
dim as double _
a = 5.1
dim as single _
b = 5.1
? a, b
? cbool( a = 5.1# ), cbool( b = 5.1! )
? cbool( a = b )
? fcomp( a, b )
sleep()
Code: Select all
const as double EPSILON = 1e-5
#define fcomp( value1, value2 ) _
iif( abs( value1 - value2 ) < EPSILON, true, false )
#define fcomp2(value1,value2) cbool(csng(value1)=csng(value2))
dim as double _
a = 5.1
dim as single _
b = 5.1
? a, b
? cbool( a = 5.1# ), cbool( b = 5.1! )
? cbool( a = b )
? fcomp( a, b )
print fcomp2( a, b )
print "----------"
a=rnd/1000
b=rnd/1000
print a,b
? fcomp( a, b )
print fcomp2( a, b )
print
b=a
print a,b
? fcomp( a, b )
print fcomp2( a, b )
sleep()
You are certainly right. In fact no floating point representation can be exact all the time. The results from my program in another language do not match exactly the results in FB despite using double throughout. I now have to resort to an old trick I used a long time ago and multiply my sums and other computations by a factor and convert to integer. Results now match perfectly. I'm only doing this to make sure the code in FB is functioning the same way as in the other language. Code conversions can be very challenging for a number of reasons.badidea wrote:I wouldn't 'trust' doubles blindly as well.