Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / lazarus / 2015-09

samevalue function issue

2 messages · 2 people ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Andrea Mauri

Dear all,

I am using samevalue function provided with fpc (math unit). I am using samevalue instead of = in order to avoid problems related to precision.

If I compare two values:

   a:= 5.1000000000000005;
   b:= 5.1;

if I use = operator I get that the two numbers are different. Using samevalue I should get that a and b are equal.

Anyway I am encountering an issue that I cannot understand, see the two code samples below:

var
a, b: Double;
begin
   a:= 5.1000000000000005;
   b:= 5.1;
   if samevalue(a, b) then              // I get TRUE - right!
     label1.Caption:= 'same value (variable): True'
   else
     label1.Caption:= 'same value (variable): False';
   if samevalue(a, 5.1) then             // I get FALSE -- I supposed to
get TRUE- bad!
     label2.Caption:= 'same value (const): True'
   else
     label2.Caption:= 'same value (const): False';
end;

why two different behaviours if I use b as a variable or as a constant?

Inversely:

var
   a, b: Double;
begin
   a:= 43.999400000000009;
   b:= 44;
   if samevalue(a, b) then              // I get FALSE - right!
     label1.Caption:= 'same value (variable): True'
   else
     label1.Caption:= 'same value (variable): False';
   if samevalue(a, 44) then             // I get TRUE -- I supposed to
get FALSE- bad!
     label2.Caption:= 'same value (const): True'
   else
     label2.Caption:= 'same value (const): False';
end;

It seems that samevalue works if I use samevalue(a, b) but not if I directly pass a number to samevalue as samevalue(a, 44). But I am not sure since I did only few tests.

Could you please provide some explanations? Why the two different behaviours? How should I use samevalue?

Let me know and best regards,
Andrea Mauri

Reply by email

Virgo Pärna
to Andrea Mauri
Andrea Mauri wrote 6 lines
Dear all, I am using samevalue function provided with fpc (math unit). I am using samevalue instead of = in order to avoid problems related to precision.

Why are you not using your own epsilon value?

if samevalue(a, 5.1) then // I get FALSE -- I supposed to get TRUE- bad!

Could you try
samevalue(a, Double(5.1))
instead?

Virgo P?rna

Reply by email