PDA

View Full Version : Forth and fractional expontents


JRobertson
07-25-00, 12:16 PM
I am programming a function in forth that needs a square root. Is there any way to program a square root in forth? I have the floating point extentions for Max-Forth, 3.x <p>thanks,

nmitech
07-25-00, 12:56 PM
The word for the square root is FSQRT<br>e.g. square root of 2<p>DECIMAL ( must set in decimal mode )<p>2E0 FSQRT F. ( it will come out 1.414223 )<br>

jya
07-30-00, 04:23 PM
If you don't need floating point, there are integer routines that you can use. Some are slow and compact, some are larger and faster. All are faster than converting to float, square rooting, and converting back. The simplest is<p>: SQRT ( u -- n ) <br> -1 TUCK DO ( n) <br> 2+ <br> DUP +LOOP <br> 2/ ;<p>Not fast, but simple. I think it originated with Chuck Moore.<p>I include 'HC11 code for TUCK in case you need it:<p>CODE TUCK ( n1 n2 -- n2 n1 n2 ) \ aka UNDER<br> 18EC , 00 C, \ LDD 0,Y n2<br> CDEE , 02 C, \ LDX 2,Y n1<br> CDEF , 00 C, \ STX 0,Y<br> 18ED , 02 C, \ STD 2,Y<br> 7E C, FE43 , \ JMP PUSHD<br>END-CODE<p>And a high-level version:<br>: TUCK ( n1 n2 -- n2 n1 n2 ) DUP &gt;R SWAP R&gt; ;<p>On a 68HC11, the CODE version takes 72 cycles, this one, 300.<p>Jerry<p>----------<br>Engineering is the art of making what you want from things you can get.<p><br>

kevinr
08-11-00, 12:28 PM
I tried :<br>DECIMAL<br>2E0 FSQRT F.<p>on my NMI 0912 board and it crashes everytime. Every time I've used FSQRT I needed to change my number into a floating point number with the S&gt;F word.

rob
08-14-00, 06:41 AM
Unfortunately, there is a bug in the C library routine sqrt() with the<br> L version of the software which causes FSQRT to fail. Fortunately, the<br> fix for it in Forth is:<p> : FSQRT (F:r1 -- r2) .5E F** ;<p> Just redefine FSQRT before you use it and you will be ok. You will<br> receive a redefinition message which can be ignored. Here are the<br> results of my tests:<p>COLD<br>Max-FORTH V5.0L<br>DECIMAL OK<br>2E0 FSQRT F. -1175.1171 OK<br>9E0 FSQRT F. -1175.1171 OK<br>: FSQRT .5E F** ;<br>FSQRT NOT UNIQUE OK<br>2E0 FSQRT F. 1.4142 OK<br>9E0 FSQRT F. 3.0000 OK<p> The current version of the C compiler used for compiling the floating<br> point words has this math library bug fixed and the unreleased version<br> of the kernel works correctly.<br>