Sujet : Re: Average of a [stack]
De : buzz_mccool (at) *nospam* yahoo.com (Buzz McCool)
Groupes : comp.lang.forthDate : 10. Jul 2024, 23:08:59
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v6n0pr$2363u$1@dont-email.me>
References : 1 2
User-Agent : Mozilla Thunderbird
On 6/7/2024 1:32 PM, LIT wrote:
: AVG DEPTH 0 SWAP DUP >R 0 DO SWAP + LOOP R> / . ;
I coincidentally was doing averaging for the floating point stack when I ran across this posting. Other than adding stack comments, how can I improve this word?
$ gforth
( Average all values on the floating point stack )
: FloatStackAvg
fdepth \ Place the number of floating point values on to the stack
>r \ Move the number of floating point values to the return stack
1 \ Initialize loop counter to 1
begin dup r@ < \ Duplicate counter, see if < fetched number of floats
while \ while true
f+ \ Add two values on the floating point stack
1 + \ Increment counter
repeat \ Repeat test at begin word
r> \ Move the number of floating point values to the stack
s>f \ Convert the number of floating point values to a float
f/ \ Divide sum by number of floating point values to get average
drop ; \ Remove the leftover loop counter value from the stack
\ Place values on floating point stack
0.120000e 0.118025e 0.118925e 0.120050e 0.119000e 0.122000e 0.120175e
0.120150e 0.118925e 0.121775e ok f:10
FloatStackAvg ok f:1
fe. 119.902500000000E-3 ok