Sum of squares: Difference between revisions
No edit summary |
No edit summary |
||
Line 71: | Line 71: | ||
=={{header|C}}== |
=={{header|C}}== |
||
<c>#include <stdio.h> |
<lang c>#include <stdio.h> |
||
double squaredsum(double *l, int e) |
double squaredsum(double *l, int e) |
||
Line 89: | Line 89: | ||
printf("%lf\n", squaredsum(NULL, 0)); |
printf("%lf\n", squaredsum(NULL, 0)); |
||
return 0; |
return 0; |
||
}</ |
}</lang> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
<cpp>#include <iostream> |
<lang cpp>#include <iostream> |
||
#include <algorithm> |
#include <algorithm> |
||
#include <vector> |
#include <vector> |
||
Line 117: | Line 117: | ||
std::cout << vec_add_squares(v) << std::endl; |
std::cout << vec_add_squares(v) << std::endl; |
||
return 0; |
return 0; |
||
}</ |
}</lang> |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
Line 125: | Line 125: | ||
=={{header|D}}== |
=={{header|D}}== |
||
<d>module sumsquare ; |
<lang d>module sumsquare ; |
||
import std.stdio ; |
import std.stdio ; |
||
Line 139: | Line 139: | ||
writefln(arr) ; |
writefln(arr) ; |
||
writefln(arr.sumsq()) ; |
writefln(arr.sumsq()) ; |
||
}</ |
}</lang> |
||
<strong style="font-size:135%;">Functional style</strong><br> |
<strong style="font-size:135%;">Functional style</strong><br> |
||
{{works with|D|2.011}} |
{{works with|D|2.011}} |
||
See [http://www.digitalmars.com/d/2.0/phobos/std_algorithm.html std.algorithm] |
See [http://www.digitalmars.com/d/2.0/phobos/std_algorithm.html std.algorithm] |
||
<d>import std.algorithm ; |
<lang d>import std.algorithm ; |
||
T sumsq(T)(inout T[] a) { |
T sumsq(T)(inout T[] a) { |
||
return reduce!("a+b")(cast(T)0, map!("a*a")(a)) ; |
return reduce!("a+b")(cast(T)0, map!("a*a")(a)) ; |
||
}</ |
}</lang> |
||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
Line 236: | Line 236: | ||
Assume the numbers are in a double array called "nums". |
Assume the numbers are in a double array called "nums". |
||
<java>... |
<lang java>... |
||
double sum = 0; |
double sum = 0; |
||
for(double a : nums){ |
for(double a : nums){ |
||
Line 242: | Line 242: | ||
} |
} |
||
System.out.println("The sum of the squares is: " + sum); |
System.out.println("The sum of the squares is: " + sum); |
||
...</ |
...</lang> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
<javascript>function sumsq(array) { |
<lang javascript>function sumsq(array) { |
||
var sum = 0; |
var sum = 0; |
||
for(var i in array) |
for(var i in array) |
||
Line 252: | Line 252: | ||
} |
} |
||
alert( sumsq( [1,2,3,4,5] ) ); // 55</ |
alert( sumsq( [1,2,3,4,5] ) ); // 55</lang> |
||
{{libheader|Functional}} |
{{libheader|Functional}} |
||
<javascript>Functional.reduce("x+y*y", 0, [1,2,3,4,5]) // 55</ |
<lang javascript>Functional.reduce("x+y*y", 0, [1,2,3,4,5]) // 55</lang> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
Line 266: | Line 266: | ||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
<ocaml>List.fold_left (fun sum a -> sum + a * a) 0 ints</ |
<lang ocaml>List.fold_left (fun sum a -> sum + a * a) 0 ints</lang> |
||
<ocaml>List.fold_left (fun sum a -> sum +. a *. a) 0. floats</ |
<lang ocaml>List.fold_left (fun sum a -> sum +. a *. a) 0. floats</lang> |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
<perl>sub sum_of_squares { |
<lang perl>sub sum_of_squares { |
||
my $sum = 0; |
my $sum = 0; |
||
$sum += $_**2 foreach @_; |
$sum += $_**2 foreach @_; |
||
Line 277: | Line 277: | ||
} |
} |
||
print sum_of_squares(3, 1, 4, 1, 5, 9), "\n";</ |
print sum_of_squares(3, 1, 4, 1, 5, 9), "\n";</lang> |
||
or |
or |
||
<perl>use List::Util qw(reduce); |
<lang perl>use List::Util qw(reduce); |
||
sub sum_of_squares { |
sub sum_of_squares { |
||
reduce { $a + $b **2 } 0, @_; |
reduce { $a + $b **2 } 0, @_; |
||
} |
} |
||
print sum_of_squares(3, 1, 4, 1, 5, 9), "\n";</ |
print sum_of_squares(3, 1, 4, 1, 5, 9), "\n";</lang> |
||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
Line 301: | Line 301: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
<python>sum([x*x for x in [1, 2, 3, 4, 5]])</ |
<lang python>sum([x*x for x in [1, 2, 3, 4, 5]])</lang> |
||
=={{header|R}}== |
=={{header|R}}== |
||
Line 308: | Line 308: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
<ruby>[3,1,4,1,5,9].inject(0) { |sum,x| sum += x*x }</ |
<lang ruby>[3,1,4,1,5,9].inject(0) { |sum,x| sum += x*x }</lang> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
<scheme>(define (sum-of-squares l) |
<lang scheme>(define (sum-of-squares l) |
||
(apply + (map * l l)))</ |
(apply + (map * l l)))</lang> |
||
> (sum-of-squares (list 3 1 4 1 5 9)) |
> (sum-of-squares (list 3 1 4 1 5 9)) |
Revision as of 15:53, 3 February 2009
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
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).
Ada
<Ada>with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Sum_Of_Squares is
type Float_Array is array (Integer range <>) of Float;
function Sum_Of_Squares (X : Float_Array) return Float is Sum : Float := 0.0; begin for I in X'Range loop Sum := Sum + X (I) ** 2; end loop; return Sum; end Sum_Of_Squares;
begin
Put_Line (Float'Image (Sum_Of_Squares ((1..0 => 1.0)))); -- Empty array Put_Line (Float'Image (Sum_Of_Squares ((3.0, 1.0, 4.0, 1.0, 5.0, 9.0))));
end Test_Sum_Of_Squares;</Ada> Sample output:
0.00000E+00 1.33000E+02
ALGOL 68
The computation can be written as a loop.
main1:( PROC sum of squares = ([]REAL argv)REAL:( REAL sum := 0; FOR i FROM LWB argv TO UPB argv DO sum +:= argv[i]**2 OD; sum ); printf(($xg(0)l$,sum of squares([]REAL(3, 1, 4, 1, 5, 9)))); )
Output:
133
Another implementation could define a procedure (PROC) or operator (OP) called map.
main2:( []REAL data = (3, 1, 4, 1, 5, 9); PROC map = ( PROC(REAL)REAL func, []REAL argv)REAL: ( REAL out:=0; FOR i FROM LWB argv TO UPB argv DO out:=func(argv[i]) OD; out); REAL sum := 0; printf(($xg(0)l$, map ( ((REAL argv)REAL: sum +:= argv ** 2), data) )); PRIO MAP = 5; # the same priority as the operators <, =<, >=, & > maybe... # OP MAP = ( PROC(REAL)REAL func, []REAL argv)REAL: ( REAL out:=0; FOR i FROM LWB argv TO UPB argv DO out:=func(argv[i]) OD; out); sum := 0; printf(($xg(0)l$, ((REAL argv)REAL: sum +:= argv ** 2) MAP data )) )
Output:
133 133
BASIC
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
C
<lang c>#include <stdio.h>
double squaredsum(double *l, int e) {
int i; double sum = 0.0; for(i = 0 ; i < e ; i++) sum += l[i]*l[i]; return sum;
}
int main() {
double list[6] = {3.0, 1.0, 4.0, 1.0, 5.0, 9.0}; printf("%lf\n", squaredsum(list, 6)); printf("%lf\n", squaredsum(list, 0)); /* the same without using a real list as if it were 0-element long */ printf("%lf\n", squaredsum(NULL, 0)); return 0;
}</lang>
C++
<lang cpp>#include <iostream>
- include <algorithm>
- include <vector>
double add_square(double prev_sum, double new_val) {
return prev_sum + new_val*new_val;
}
double vec_add_squares(std::vector<double>& v) {
return std::accumulate(v.begin(), v.end(), 0.0, add_square);
}
int main() {
// first, show that for empty vectors we indeed get 0 std::vector<double> v; // empty std::cout << vec_add_squares(v) << std::endl;
// now, use some values double data[] = { 0, 1, 3, 1.5, 42, 0.1, -4 }; v.assign(data, data+7); std::cout << vec_add_squares(v) << std::endl; return 0;
}</lang>
Common Lisp
(defun sum-of-squares (vector) (loop for x across vector sum (expt x 2)))
D
<lang d>module sumsquare ; import std.stdio ;
T sumsq(T)(T[] a) {
T sum = 0 ; foreach(e ; a) sum += e*e ; return sum ;
}
void main() {
real[] arr = [3.1L,1,4,1,5,9] ; writefln(arr) ; writefln(arr.sumsq()) ;
}</lang>
Functional style
See std.algorithm <lang d>import std.algorithm ; T sumsq(T)(inout T[] a) {
return reduce!("a+b")(cast(T)0, map!("a*a")(a)) ;
}</lang>
Erlang
lists:foldl(fun(X, Sum) -> X*X + Sum end, 0, [3,1,4,1,5,9]).
Forth
: fsum**2 ( addr n -- f ) 0e dup 0= if 2drop exit then floats bounds do i f@ fdup f* f+ 1 floats +loop ; create test 3e f, 1e f, 4e f, 1e f, 5e f, 9e f, test 6 fsum**2 f. \ 133.
Fortran
In ISO Fortran 90 orlater, use SUM intrinsic and implicit element-wise array arithmetic:
real, dimension(1000) :: a = (/ (i, i=1, 1000) /) real, pointer, dimension(:) :: p => a(2:1) ! pointer to zero-length array real :: result, zresult result = sum(a*a) ! Multiply array by itself to get squares result = sum(a**2) ! Use exponentiation operator to get squares zresult = sum(p*p) ! P is zero-length; P*P is valid zero-length array expression; SUM(P*P) == 0.0 as expected
Haskell
sumOfSquares = sum . map (^ 2)
> sumOfSquares [3,1,4,1,5,9] 133
IDL
print,total(array^2)
Icon
procedure main() local lst lst := [] #Construct a simple list and pass it to getsum every put(lst,seq()\2) write(getsum(lst)) end procedure getsum(lst) local total total := 0 every total +:= !lst ^ 2 return total end
Io
list(3,1,4,1,5,9) map(squared) sum
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".
<lang java>... double sum = 0; for(double a : nums){
sum+= a * a;
} System.out.println("The sum of the squares is: " + sum); ...</lang>
JavaScript
<lang javascript>function sumsq(array) {
var sum = 0; for(var i in array) sum += array[i] * array[i]; return sum; } alert( sumsq( [1,2,3,4,5] ) ); // 55</lang>
<lang javascript>Functional.reduce("x+y*y", 0, [1,2,3,4,5]) // 55</lang>
Logo
print apply "sum map [? * ?] [1 2 3 4 5] ; 55
Maxima
nums : [3,1,4,1,5,9]; sum(nums[i]^2,i,1,length(nums));
OCaml
<lang ocaml>List.fold_left (fun sum a -> sum + a * a) 0 ints</lang>
<lang ocaml>List.fold_left (fun sum a -> sum +. a *. a) 0. floats</lang>
Perl
<lang perl>sub sum_of_squares {
my $sum = 0; $sum += $_**2 foreach @_; return $sum;
}
print sum_of_squares(3, 1, 4, 1, 5, 9), "\n";</lang> or <lang perl>use List::Util qw(reduce); sub sum_of_squares {
reduce { $a + $b **2 } 0, @_;
}
print sum_of_squares(3, 1, 4, 1, 5, 9), "\n";</lang>
Pop11
define sum_squares(v); lvars s = 0, j; for j from 1 to length(v) do s + v(j)*v(j) -> s; endfor; s; enddefine; sum_squares({1 2 3 4 5}) =>
Python
<lang python>sum([x*x for x in [1, 2, 3, 4, 5]])</lang>
R
arr <- c(1,2,3,4,5) result <- sum(arr^2)
Ruby
<lang ruby>[3,1,4,1,5,9].inject(0) { |sum,x| sum += x*x }</lang>
Scheme
<lang scheme>(define (sum-of-squares l)
(apply + (map * l l)))</lang>
> (sum-of-squares (list 3 1 4 1 5 9)) 133
UnixPipes
folder() { (read B; res=$( expr $1 \* $1 ) ; test -n "$B" && expr $res + $B || echo $res) }
fold() { (while read a ; do fold | folder $a done) }
(echo 3; echo 1; echo 4;echo 1;echo 5; echo 9) | fold
V
[sumsq [dup *] map 0 [+] fold].
[] sumsq =0 [1 2 3] sumsq =14