12.23Floating point functions. 4tH 4tH Forth compiler
Annonce
Annonce
CHAPTER 12. STANDARD LIBRARIES 197
Defining constants this way is about four times faster. This is especially useful when you need a constant in a tight loop. Note that the exponent must be in the range of -24 to 24, otherwise you won’t get the correct result.
Most ANS-Forth floating point words are available, although these words usually have their own library file. For technical reasons they will not automatically include the floating point number library for you, but abort instead if it is not loaded. So if you want to calculate the sine of 45 degrees, you have to do this: include lib/ansfloat.4th
include lib/ansfpio.4th
include lib/fsinfcos.4th
fclear
8 set-precision pi 4 s>f f/ fsin f. cr
\ include the fp library
\ include the fp i/o library
\ include the library
\ clear the fp stack
\ set precision to eight
\ calculate the sine
Since a full circle (360 degrees) requires 2 times PI, we have to divide it by 4 to get the equivalent in radians
23
. But what if you make an error? What if a conversion overflows, you divide by zero or try to get the square root of a negative number? There is where
”FERROR” comes in. It is a variable that holds the last floating point error that occurred.
Here you got an example: include lib/ansfloat.4th
include lib/ansfpio.4th
fclear
8 set-precision
1 s>f 0 s>f f/ ferror ? cr
\ include the library
\ include the fp i/o library
\ clear the fp stack
\ set precision to eight
\ divide by zero
\ examine FERROR
In this case, ”FERROR” returns two. But what does that mean? Well, here you got a handy table of all IEEE 754 exceptions. In 4tH, these are predefined constants.
C
ODE
M
EANING
FE.NOERRORS
No error
FE.OVERFLOW
FP overflow
FE.UNDERFLOW
FP underflow
FE.DIVBYZERO
Division by zero
FE.INEXACT
FE.INVALID
Inexact result
Invalid operation
Table 12.9: IEEE 754 FP math errors
You can simply clear any errors by invoking ”FCLEAR” again. Note that this clears your floating point stack too, so you have to start all over again. And no, ’THROW’ and
’CATCH’ do not restore your floating point stack. No easy recovery here!
12.23
Floating point functions
ANS-Forth floating point comes with a large number of libraries, sometimes two or more for the same mathematical function. Table 12.10 may help you to select the proper one for your specific problem.
23
”FSIN” takes its parameter in radians.
Download
Annonce