One condition is, I don't know the total length of an array because it will be changed every time. Maybe I could write down as (although it looks complicated..),
(setf total-value 0) (loop for i from 0 to arr-index do (setf total-value (+ total-value (aref arr i))) finally (setf ave-value (/ total-value (+ arr-index 1))))
However, I just wonder that is there any function or macro which can add whole values in an array? I want use this function with one simple line.... I couldn't find that kind of things, but maybe something exist? Thanks for advance. =)
> I would like to get an average value of an array.
> Let's say, an Array R := (1 2 3 4 5 6 7 8 9 10)
(/ (reduce #'+ R) (length R))
Watch out for zero-length arrays.
-----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! -----== Over 80,000 Newsgroups - 16 Different Servers! =-----
> I would like to get an average value of an array.
> Let's say, an Array R := (1 2 3 4 5 6 7 8 9 10)
> One condition is, I don't know the total length of an array because it will > be changed every time. Maybe I could write down as (although it looks > complicated..),
do you mean an array or do you mean a list?
because if it's really an array, you can get its dimension easily. reduce #'+ can sum a vector.
this can be extended to handle more dimensions, but you get the idea.
> (setf total-value 0) > (loop for i from 0 to arr-index > do (setf total-value (+ total-value (aref arr i))) > finally (setf ave-value (/ total-value (+ arr-index 1))))
> However, I just wonder that is there any function or macro which can add > whole values in an array? I want use this function with one simple line.... I > couldn't find that kind of things, but maybe something exist? Thanks for > advance. =)
yes, it give me right answer. I little bit worried about the meaning of the word 'REDUCE'. If 'REDUCE' function actually reduce the array size, it is not suitable for me... But after took a look the reference my silly worries gone. =) Thanks =)
* sung...@cad.strath.ac.uk | One condition is, I don't know the total length of an array because it | will be changed every time. Maybe I could write down as (although it | looks complicated..), | | (setf total-value 0) | (loop for i from 0 to arr-index | do (setf total-value (+ total-value (aref arr i))) | finally (setf ave-value (/ total-value (+ arr-index 1)))) | | However, I just wonder that is there any function or macro which can | add whole values in an array? I want use this function with one | simple line.... I couldn't find that kind of things, but maybe | something exist? Thanks for advance. =)
I should give you the hints and the pointers, but I'm tired, so here's how you compute the average of a vector of numbers:
(/ (reduce #'+ <vector>) (length <vector>))
Incidentally, the standard deviation is also very useful if you ever work with averages: