Sum of squares: Difference between revisions
Content added Content deleted
(-> IDL) |
(Added BASIC example) |
||
Line 1: | Line 1: | ||
{{task}} |
{{task}} |
||
Write a program to find the sum of squares of a numeric vector. |
Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of 0). |
||
The program should work on a zero-length vector (with an answer of 0). |
|||
=={{header|BASIC}}== |
|||
'''Compiler''': [[QuickBasic]] 4.5 |
|||
Assume the numbers are in a <tt>DIM</tt> called <tt>a</tt>. |
|||
sum = 0 |
|||
FOR I = LBOUND(a) TO UBOUND(a) |
|||
sum = sum + a(I) ^ 2 |
|||
NEXT I |
|||
PRINT "The sum of squares is: " + sum |
|||
=={{header|IDL}}== |
=={{header|IDL}}== |
Revision as of 02:11, 30 January 2008
Sum of squares
You are encouraged to solve this task according to the task description, using any language you may know.
You are encouraged to solve this task according to the task description, using any language you may know.
Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of 0).
BASIC
Compiler: QuickBasic 4.5 Assume the numbers are in a DIM called a.
sum = 0 FOR I = LBOUND(a) TO UBOUND(a) sum = sum + a(I) ^ 2 NEXT I PRINT "The sum of squares is: " + sum
IDL
print,total(array^2)
J
ss=: +/ @: *:
That is, sum composed with square. The verb also works on higher-ranked arrays. For example:
ss 3 1 4 1 5 9 133 ss $0 NB. $0 is a zero-length vector 0 x=: 20 4 ?@$ 0 NB. a 20-by-4 table of random (0,1) numbers ss x 9.09516 5.19512 5.84173 6.6916
The computation can also be written as a loop. It is shown here for comparison only and is highly non-preferred compared to the version above.
ss1=: 3 : 0 z=. 0 for_i. i.#y do. z=. z+*:i{y end. ) ss1 3 1 4 1 5 9 133 ss1 $0 0 ss1 x 9.09516 5.19512 5.84173 6.6916
Java
Assume the numbers are in a double array called "nums".
... double sum = 0; for(double a : nums){ sum+= a * a; } System.out.println("The sum of the squares is: " + sum); ...