home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Power-Programmierung
/
CD1.mdf
/
forth
/
compiler
/
fpc
/
source
/
l5p030.seq
< prev
next >
Wrap
Text File
|
1990-04-17
|
3KB
|
91 lines
\ Lesson 5 Part 3 ( F-PC 3.5 Tutorial by Jack Brown )
\ One way to use */ is in the rational approximations to common
\ constants. These are from Starting Forth page 122 1st ed, p109 2nd ed.
: *PI 355 113 */ ;
: *SQRT(2) 19601 13860 */ ;
: *SQRT(3) 18817 10864 */ ;
: *E 28667 10546 */ ;
\ Problem 5.2
\ If you are going to use integer arithmetic in you programs part of
\ your responsibility is to make sure both you and your users know what
\ the range of valid inputs each word or program. Consider the simple
\ programs given below. For each of these find the smallest and largest
\ values of the inputs that will still give valid results.
\ Area of circle
: AREA ( r -- a ) DUP * *PI ;
\ Volume of sphere v = pi*r*r*r*4/3
: VS ( r -- vol ) DUP DUP * * *PI 4 3 */ ;
\ Volume of a cone. v = pi*r*r*h/3
: VC ( h r -- vol ) AREA SWAP 3 */ ;
\ Diagonal of a square. d=s*sqrt(2)
: DI ( s -- diagonal ) *SQRT(2) ;
\ Height of an equilateral triangle. h = s*sqrt(3)/2
: HI ( s -- height ) *SQRT(3) 2/ ;
\ Even though you are restricted to working with integers you can still do
\ fractional artimetic. Here is a brute force approch to displaying
\ fractions of the form m/n where m and n are on the stack and improper
\ fractions of the form i+m/n where i m and n are on the stack and i is an
\ integer.
\ Brute force approach to fractions.
\ Display decimal equivalent of fraction m/n.
: .XXX ( m n -- )
2DUP > ABORT" Improper fraction." \ require m < n
>R 2000 R> */ 1+ 2/ ( Scale and round fraction )
ASCII . EMIT DUP 10 <
IF ASCII 0 DUP EMIT EMIT
ELSE DUP 100 <
IF ASCII 0 EMIT
THEN
THEN . ;
\ Print the decimal equivalent of the mixed fraction i+m/n
: I.XXX ( i m n -- )
ROT 5 .R .XXX ;
\ Display decimal equivalents of 1/n through (n-1)/n
: TEST ( n -- )
CR DUP 1
?DO CR I OVER 2DUP SWAP
. ." /" . ." = " .XXX
LOOP DROP ;
\ */MOD a relative of */ ....
\ This word takes the same stack inputs as */ but leaves both the
\ remainder and the quotient.
\ */MOD ( a b c -- rem(ab/c) quot(ab/c) )
\ Compute ab/c with 32bit intermediate product ab and leave quotient
\ q and remainder r . Note: Forth-83 */MOD uses signed values a b c
\ and uses floored division. */MOD ( a b c -- r q )
\ Example:
\ Calculate area of a circle and display to 3 decimal places.
: .AREA ( r -- )
DUP * 355 113 \ This is ratio for pi
*/MOD SWAP 113 \ We need remainder for I.XXX
." The area of the circle is " I.XXX ;
\ Example:
\ Calculate volume of a sphere and display to 3 decimals.
: .VOLUME ( r -- )
DUP DUP * SWAP 1420 * ( r*r r*1420 )
339 */MOD SWAP 339
." The volume of the sphere is " I.XXX ;
\ Problem 5.3
\ Write words that will calculate the surfacer area of a sphere and the
\ volume of a cone and display the answers to three decimal places.