Forth

From Noisebridge Wiki
Revision as of 04:44, 10 February 2026 by Maintenance script (talk | contribs) (Imported from Noisebridge wiki backup)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

sample[edit]

2 + 2

2
2
+
.

result 4


9 % 4

9
4
/mod
.s

result 1 2


square word

: sq dup * ;
2 sq
.s

result 4


hello world

: hw ." hello world" ;
hw

result hello world


integer square root

-1
variable x
256 x !
variable g
1 g ! 
: r x @ g @ / ;
: a g @ + 2/ g ! ;
: t r a g @ .s ;
: c over over = . ;
t c
...
t c

result

t c <2> -1 128 0  ok
t c <3> -1 128 65 0  ok
t c <4> -1 128 65 34 0  ok
t c <5> -1 128 65 34 20 0  ok
t c <6> -1 128 65 34 20 16 0  ok
t c <7> -1 128 65 34 20 16 16 -1  ok


integer square root

: a + 2/ ;
: sq dup * ;
: sc 2dup sq < if 0 else 2dup 1+ sq < then ;
: nsqrt 1 begin sc if swap drop exit then 2dup / a again ;
100 nsqrt .

result 10


fix point 1 sqrt

...
: pt 8 emit 46 emit ;
: fixpt1 10 /mod . pt . ;
: xsqrt 100 * nsqrt fixpt1 ;
3 xsqrt

result 1.7


fix point 2 sqrt

...
: xxsqrt 10000 * nsqrt fixpt2 ;  ok
33 xxsqrt

result 5.74


print square root

...
: psqrt dup 42949672 > if nsqrt . else dup 429496 > if xsqrt else xxsqrt then then ;
123 psqrt
1234567 psqrt
123456789 psqrt

result 11.09, 1111.1, 11111

links[edit]

http://amforth.sourceforge.net/

AmForth, Floating point and ATmega implementation:

Pygmy Forth: http://pygmy.utoh.org/riscy/