TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: Bill Birrell
from: Pascal Schmidt
date: 2004-04-25 13:15:58
subject: Squares

Hi Bill! :-)

 BB>     No, Pascal. Squares of integers can not be negative. Why is this 
 BB> so difficult to understand?
Integers on a computer vs. integers in mathematics. They're not the same.
On a computer, you have to ask what happens when you do a multiplication
and the result doesn't fit into the result register on the CPU, and there's
also the question of how you later look at the result.

On an x86 CPU, when doing a 32-bit multiply instruction, the result is
actually the real mathematical result modulo 2^32. You get mathematically
perfect results, but only the last 32 bits thereof. The rest is lost, and
there is no way to find out that an overflow occured from the C level of
things.

So, theoretically speaking, the square doesn't go negative, we just don't
get all the bits on a computer doing int maths. When the (truncated) result
of an int multiplication is later viewed as an unsigned int, the result may
*appear* to be negative, precisely when the highest bit happened to be set
to 1 by the multiplication.

In conclusion, when writing a program that computes squares, don't be
surprised if you get strange results when you use ints.

Ciao
Pascal

--- Msged/LNX 6.1.1
* Origin: let fun a b c d = b (c,d) in a op < 17 end 23 (1:153/401.2)
SEEN-BY: 633/267 270
@PATH: 153/401 307 140/1 106/2000 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.