August 21, 2019

Using Forth for float calculations

Some newbies may assume, that Forth isn't able to handle float variables very well. The reason is, that the normal stack only support integer values which are not able to express a fraction of a number. Handling float variables is possible with the dedicated float stack. In Gforth an example program would look like:

3.e \ put 3.0 to the float stack
7.e \ put 7.0 to the float stack
f.s \ show content of float stack
f/  \ 3.0/7.0
f.  \ retrieves the top element of float stack
0.428571428571429  \ the result of the calculation

\ it's  possible to shorten up the calcuation drastically
3e 7e f/ f.
0.428571428571429

\ lets try something more complicated
3.14e 3.e f* fsqrt f.  \ sqrt(3.14*3)
3.06920185064456  \ the result is correct

The examples have shown, that Forth is ready for handling floating point operations.

No comments:

Post a Comment