Square Root of Negative Number Bug

One of the Newton 2.x OS Q&As
Copyright © 1997 Newton, Inc. All Rights Reserved. Newton, Newton Technology, Newton Works, the Newton, Inc. logo, the Newton Technology logo, the Light Bulb logo and MessagePad are trademarks of Newton, Inc. and may be registered in the U.S.A. and other countries. Windows is a registered trademark of Microsoft Corp. All other trademarks and company names are the intellectual property of their respective owners.


For the most recent version of the Q&As on the World Wide Web, check the URL: http://www.newton-inc.com/dev/techinfo/qa/qa.htm
If you've copied this file locally, click here to go to the main Newton Q&A page.
This document was exported on 7/23/97.


Square Root of Negative Number Bug (3/4/97)

Q: When I call Sqrt with a negative number on the Newton, or use Compile in the NTK Inspector, I get a strange result. However, if I just type sqrt(-2) into the listener I get a different strange result. What's going on?

    call compile("sqrt(-2)") with ()
    #4412F2D  -1.79769e+308

    sqrt(-2)
    #440DE05  1.00000e+999


A: There is a floating point library bug in Sqrt on the Newton OS. When passed a negative number, the large positive value is returned instead of a not-a-number value. You can work around it using Pow(x, 0.5) instead of Sqrt(x) if there is no way to guarantee that the value passed to Sqrt is non-negative, or simply check and see if the argument is less than 0 and return a not-a-number constant.

The reason sqrt(-2) works differently when you type it into the NTK Inspector is because of a compiler process known as constant folding. Sqrt can be evaluated at compile time if you pass it a constant argument. So what's really happening is that NTK is evaluating the Sqrt function during the compile phase and passing the resulting floating point number (or rather, not-a-number) to the Newton device where it's promptly returned. An NTK real number formatting limitation displays non-a-number values and infinities as 1.00000e+999 rather than as some other string. You can use IsNAN to determine if a real number is a not-a-number value.

You can avoid constant folding and force evaluation on the Newton device by using a variable. For instance:
    x := -2;
    y := sqrt(x);
    #C4335B1  -1.79769e+308


Also, note that FormattedNumberStr does not properly handle not-a-number values. (it returns "Number too small.")