Newsgroups: comp.lang.pascal
Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!van-bc!ubc-cs!newsserver.sfu.ca!shephard
From: shephard@newsserver.sfu.ca (Gordon Shephard)
Subject: Re: Is this a bug in TurboPascal
Message-ID: <1991May1.060345.26511@newsserver.sfu.ca>
Organization: Simon Fraser University, Burnaby, B.C., Canada
References: <1991May1.021059.2129@ux1.cso.uiuc.edu>
Date: Wed, 1 May 91 06:03:45 GMT
Lines: 39


>var
>    xx,yy,c1,c2,c3,c4: integer;

>begin
>    xx := 639; yy := 479; 
>    c1 := Trunc(50*xx/639); c2 := Trunc(50*yy/479);
>    c3 := Trunc(300*xx/639); c4 := Trunc(250*yy/479);
>    writeln(xx,yy,c1,c2,c3,c4);
>end.

>OUTPUT:
>639,479,50,50,-7,-23

>How does it happen that the last two numbers are wrong and the rest right???

In Turbo Pascal, An Integer can take on the values from -32768 to 32767.
This is because An integer is only two bytes long, and therefore can
only take on 65536 values. 2^16.
TP also operates in the Lowest Common Denominator when Doing Arithmetic.
E.G. All of your variables are integers, so TP worked with integers.
(Note, if you'd have multiplied by 300.0 and 250.0, always a good habit
when you risk overflow, The answers would have been correct.)
When you multiplied 300*639, your answer is 191700.  So not only do you
wrap around to the negative values (32767+1=-32768 in integer
arithmetic.  Just like a speedometer), you also lose some data
(overflow).  In Hexdecimal, 191700=$2ECD4, of which only the $ECD4 is
stored.  $ECD4=-4908 as an integer. Trunc (-4908/639) = -7.
 
 The easiest way around all of this is to add .0 to at least one number
 in an equation which could cause trouble.  This forces TP to perform
 Real Arithmetic on the numbers involved


-- 
| Gordon Harry Shephard         | Distributed Computing Support Group  |
| Academic Computing Services   | Phone: (604)291-3930   (604)464-4991 | 
| Simon Fraser University       | USERGHS@SFU.BITNET                   |
| Burnaby, BC, Canada. V5A 1S6  | Shephard@Whistler.sfu.ca             | 
