BBC BASIC for Windows
Programming >> BBC BASIC language >> Subtraction
http://bb4w.conforums.com/index.cgi?board=language&action=display&num=1487267624

Subtraction
Post by JB91 on Feb 16th, 2017, 4:53pm

Hello,

Can somebody please tell me why the following IF statement does not display the text "Hello!"? I guess it's something to do with the numbers not being integers, but I'm not sure...

Code:
IF 0.3 - 0.2 = 0.1 THEN
PRINT "Hello!"
ENDIF 


Thanks,
Josh
Re: Subtraction
Post by Zaphod on Feb 16th, 2017, 5:05pm

Yes, the answer is that computers use floating point calculations so the result is not actually 0.1 but probably something like 0.0999999999998 and therefore fails the test.
Try PRINT 0.3-0.2-0.1
It should be zero but isn't exactly.

Integer arithmetic works, decimal does not exactly but may differ in the last digits that you can't see most of the time.
So you either need to bump up the numbers to be integers or look for the result to be between defined bands that allow for the error.

You can use something like ABS( result -target)< precision needed.
IF ABS(X-0.1)< 0.001

Re: Subtraction
Post by JB91 on Feb 16th, 2017, 7:39pm

Thanks Zaphod; it makes sense to me now.

Something like this seems to fix the problem:

Code:
IF FNroundto1dp(0.3 - 0.2) = 0.1 THEN
  PRINT "Hello!"
ENDIF

END

DEF FNroundto1dp(num)
num% = num*10
= num%/10 

Re: Subtraction
Post by Zaphod on Feb 16th, 2017, 8:53pm

Now be very careful as when you assign a floating point number to an integer variable then it truncates the decimal part.

If the rounding error in the floating point variable is just over the next integer value it will give a different result to being just under. So your solution may sometimes be off by 0.1

So to truly round you would need to do this:

Code:
DEF FNroundto1dp(num) : =INT(num*10+0.5)/10
  



Re: Subtraction
Post by JB91 on Feb 16th, 2017, 9:17pm

Quote:
So your solution may sometimes be off by 0.1

Yeah I noticed that...

That rounding technique does looks familiar - I'll remember it from now on!

Thanks for your help,

Josh
Re: Subtraction
Post by KenDown on Apr 26th, 2017, 1:23pm

Another way is to convert the numbers to strings.

IFSTR$(0.3-0.2)=STR$(0.1)VDU7

I believe that the conversion process does the necessary rounding up for you.