Dot product: Difference between revisions

Content added Content deleted
(Dot product in BASIC256)
m (syntax highlighting fixup automation)
Line 23: Line 23:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>print(dot((1, 3, -5), (4, -2, -1)))</lang>
<syntaxhighlight lang="11l">print(dot((1, 3, -5), (4, -2, -1)))</syntaxhighlight>
{{out}}<pre>3</pre>
{{out}}<pre>3</pre>


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
<lang 360asm>* Dot product 03/05/2016
<syntaxhighlight lang="360asm">* Dot product 03/05/2016
DOTPROD CSECT
DOTPROD CSECT
USING DOTPROD,R15
USING DOTPROD,R15
Line 50: Line 50:
PG DC CL80' ' buffer
PG DC CL80' ' buffer
YREGS
YREGS
END DOTPROD</lang>
END DOTPROD</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 57: Line 57:


=={{header|8th}}==
=={{header|8th}}==
<lang Forth>[1,3,-5] [4,-2,-1] ' n:* ' n:+ a:dot . cr</lang>
<syntaxhighlight lang="forth">[1,3,-5] [4,-2,-1] ' n:* ' n:+ a:dot . cr</syntaxhighlight>
{{out}}<pre>3</pre>
{{out}}<pre>3</pre>


=={{header|ABAP}}==
=={{header|ABAP}}==
<lang ABAP>report zdot_product
<syntaxhighlight lang="abap">report zdot_product
data: lv_n type i,
data: lv_n type i,
lv_sum type i,
lv_sum type i,
Line 86: Line 86:
lv_sum = lv_sum + ( <wa_a> * <wa_b> ).
lv_sum = lv_sum + ( <wa_a> * <wa_b> ).
enddo.
enddo.
endform.</lang>
endform.</syntaxhighlight>
{{out}}<pre>3</pre>
{{out}}<pre>3</pre>


=={{header|ACL2}}==
=={{header|ACL2}}==
<lang Lisp>(defun dotp (v u)
<syntaxhighlight lang="lisp">(defun dotp (v u)
(if (or (endp v) (endp u))
(if (or (endp v) (endp u))
0
0
(+ (* (first v) (first u))
(+ (* (first v) (first u))
(dotp (rest v) (rest u)))))</lang>
(dotp (rest v) (rest u)))))</syntaxhighlight>


<pre>&gt; (dotp '(1 3 -5) '(4 -2 -1))
<pre>&gt; (dotp '(1 3 -5) '(4 -2 -1))
Line 100: Line 100:


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>INT FUNC DotProduct(INT ARRAY v1,v2 BYTE len)
<syntaxhighlight lang="action!">INT FUNC DotProduct(INT ARRAY v1,v2 BYTE len)
BYTE i,res
BYTE i,res


Line 141: Line 141:


Test(v1,v2,3)
Test(v1,v2,3)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Dot_product.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Dot_product.png Screenshot from Atari 8-bit computer]
Line 149: Line 149:


=={{header|ActionScript}}==
=={{header|ActionScript}}==
<lang ActionScript>function dotProduct(v1:Vector.<Number>, v2:Vector.<Number>):Number
<syntaxhighlight lang="actionscript">function dotProduct(v1:Vector.<Number>, v2:Vector.<Number>):Number
{
{
if(v1.length != v2.length) return NaN;
if(v1.length != v2.length) return NaN;
Line 157: Line 157:
return sum;
return sum;
}
}
trace(dotProduct(Vector.<Number>([1,3,-5]),Vector.<Number>([4,-2,-1])));</lang>
trace(dotProduct(Vector.<Number>([1,3,-5]),Vector.<Number>([4,-2,-1])));</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
<lang Ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
procedure dot_product is
procedure dot_product is
type vect is array(Positive range <>) of Integer;
type vect is array(Positive range <>) of Integer;
Line 178: Line 178:
begin
begin
put_line(Integer'Image(dotprod(v1,v2)));
put_line(Integer'Image(dotprod(v1,v2)));
end dot_product;</lang>
end dot_product;</syntaxhighlight>
{{out}}<pre>3</pre>
{{out}}<pre>3</pre>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>real
<syntaxhighlight lang="aime">real
dp(list a, list b)
dp(list a, list b)
{
{
Line 202: Line 202:


0;
0;
}</lang>
}</syntaxhighlight>
{{out}}<pre>3</pre>
{{out}}<pre>3</pre>


Line 210: Line 210:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<lang algol68>MODE DOTFIELD = REAL;
<syntaxhighlight lang="algol68">MODE DOTFIELD = REAL;
MODE DOTVEC = [1:0]DOTFIELD;
MODE DOTVEC = [1:0]DOTFIELD;


Line 247: Line 247:


print(("a SSDOT b = ",fixed(a SSDOT b,0,real width), new line));
print(("a SSDOT b = ",fixed(a SSDOT b,0,real width), new line));
print(("a * b = ",fixed(a * b,0,real width), new line))</lang>
print(("a * b = ",fixed(a * b,0,real width), new line))</syntaxhighlight>
{{out}}<pre>a SSDOT b = 3.000000000000000
{{out}}<pre>a SSDOT b = 3.000000000000000
a * b = 3.000000000000000</pre>
a * b = 3.000000000000000</pre>


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% computes the dot product of two equal length integer vectors %
% computes the dot product of two equal length integer vectors %
% (single dimension arrays ) the length of the vectors must be specified %
% (single dimension arrays ) the length of the vectors must be specified %
Line 275: Line 275:
write( integerDotProduct( v1, v2, 3 ) )
write( integerDotProduct( v1, v2, 3 ) )
end.
end.
</syntaxhighlight>
</lang>


=={{header|APL}}==
=={{header|APL}}==
<lang APL>1 3 ¯5 +.× 4 ¯2 ¯1</lang>
<syntaxhighlight lang="apl">1 3 ¯5 +.× 4 ¯2 ¯1</syntaxhighlight>
<b>Output:</b>
<b>Output:</b>
<pre>3</pre>
<pre>3</pre>
Line 284: Line 284:
=={{header|AppleScript}}==
=={{header|AppleScript}}==
{{trans|JavaScript}} ( functional version )
{{trans|JavaScript}} ( functional version )
<lang AppleScript>----------------------- DOT PRODUCT -----------------------
<syntaxhighlight lang="applescript">----------------------- DOT PRODUCT -----------------------


-- dotProduct :: [Number] -> [Number] -> Number
-- dotProduct :: [Number] -> [Number] -> Number
Line 371: Line 371:
return lst
return lst
end tell
end tell
end zipWith</lang>
end zipWith</syntaxhighlight>
{{Out}}
{{Out}}
<syntaxhighlight lang="applescript">3</syntaxhighlight>
<lang AppleScript>3</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>dotProduct: function [a,b][
<syntaxhighlight lang="rebol">dotProduct: function [a,b][
[ensure equal? size a size b]
[ensure equal? size a size b]


Line 388: Line 388:


print dotProduct @[1, 3, neg 5] @[4, neg 2, neg 1]
print dotProduct @[1, 3, neg 5] @[4, neg 2, neg 1]
print dotProduct [1 2 3] [4 5 6]</lang>
print dotProduct [1 2 3] [4 5 6]</syntaxhighlight>


{{out}}
{{out}}
Line 396: Line 396:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>Vet1 := "1,3,-5"
<syntaxhighlight lang="autohotkey">Vet1 := "1,3,-5"
Vet2 := "4 , -2 , -1"
Vet2 := "4 , -2 , -1"
MsgBox % DotProduct( Vet1 , Vet2 )
MsgBox % DotProduct( Vet1 , Vet2 )
Line 412: Line 412:
Sum += ArrayA%A_Index% * ArrayB%A_Index%
Sum += ArrayA%A_Index% * ArrayB%A_Index%
Return Sum
Return Sum
}</lang>
}</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f DOT_PRODUCT.AWK
# syntax: GAWK -f DOT_PRODUCT.AWK
BEGIN {
BEGIN {
Line 433: Line 433:
return(sum)
return(sum)
}
}
</syntaxhighlight>
</lang>
{{out}}<pre>3</pre>
{{out}}<pre>3</pre>


Line 439: Line 439:
==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
Calculates the dot product of two random vectors of length N.
Calculates the dot product of two random vectors of length N.
<lang basic>
<syntaxhighlight lang="basic">
100 :
100 :
110 REM DOT PRODUCT
110 REM DOT PRODUCT
Line 460: Line 460:
440 PRINT "] . [";: FOR I = 1 TO N: PRINT " ";V2(I);: NEXT I
440 PRINT "] . [";: FOR I = 1 TO N: PRINT " ";V2(I);: NEXT I
450 PRINT "] = ";DP
450 PRINT "] = ";DP
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>]RUN
<pre>]RUN
Line 469: Line 469:
==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
BBC BASIC has a built-in dot-product operator:
BBC BASIC has a built-in dot-product operator:
<lang bbcbasic> DIM vec1(2), vec2(2), dot(0)
<syntaxhighlight lang="bbcbasic"> DIM vec1(2), vec2(2), dot(0)
vec1() = 1, 3, -5
vec1() = 1, 3, -5
Line 475: Line 475:
dot() = vec1() . vec2()
dot() = vec1() . vec2()
PRINT "Result is "; dot(0)</lang>
PRINT "Result is "; dot(0)</syntaxhighlight>
{{out}}<pre>Result is 3</pre>
{{out}}<pre>Result is 3</pre>


=={{header|BASIC256}}==
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
{{trans|FreeBASIC}}
<lang BASIC256>dim zero3d = {0.0, 0.0, 0.0}
<syntaxhighlight lang="basic256">dim zero3d = {0.0, 0.0, 0.0}
dim zero5d = {0.0, 0.0, 0.0, 0.0, 0.0}
dim zero5d = {0.0, 0.0, 0.0, 0.0, 0.0}
dim x = {1.0, 0.0, 0.0}
dim x = {1.0, 0.0, 0.0}
Line 503: Line 503:
next i
next i
return dp
return dp
end function</lang>
end function</syntaxhighlight>


=={{header|bc}}==
=={{header|bc}}==
<lang bc>/* Calculate the dot product of two vectors a and b (represented as
<syntaxhighlight lang="bc">/* Calculate the dot product of two vectors a and b (represented as
* arrays) of size n.
* arrays) of size n.
*/
*/
Line 524: Line 524:
b[1] = -2
b[1] = -2
b[2] = -1
b[2] = -1
d(a[], b[], 3)</lang>
d(a[], b[], 3)</syntaxhighlight>


{{Out}}
{{Out}}
Line 530: Line 530:


=={{header|BCPL}}==
=={{header|BCPL}}==
<lang bcpl>get "libhdr"
<syntaxhighlight lang="bcpl">get "libhdr"


let dotproduct(A, B, len) = valof
let dotproduct(A, B, len) = valof
Line 543: Line 543:
let B = table 4, -2, -1
let B = table 4, -2, -1
writef("%N*N", dotproduct(A, B, 3))
writef("%N*N", dotproduct(A, B, 3))
$)</lang>
$)</syntaxhighlight>
{{out}}
{{out}}
<pre>3</pre>
<pre>3</pre>


=={{header|Befunge 93}}==
=={{header|Befunge 93}}==
<lang befunge>
<syntaxhighlight lang="befunge">
v Space for variables
v Space for variables
v Space for vector1
v Space for vector1
Line 569: Line 569:
>00g1-10p>10g:01-` | "
>00g1-10p>10g:01-` | "
> ^
> ^
</syntaxhighlight>
</lang>
{{out}}<pre>Length:
{{out}}<pre>Length:
3
3
Line 583: Line 583:


Multiply the two vectors, then sum the result.
Multiply the two vectors, then sum the result.
<lang bqn>•Show 1‿3‿¯5 +´∘× 4‿¯2‿¯1
<syntaxhighlight lang="bqn">•Show 1‿3‿¯5 +´∘× 4‿¯2‿¯1


# as a tacit function
# as a tacit function
DotP ← +´×
DotP ← +´×
•Show 1‿3‿¯5 DotP 4‿¯2‿¯1</lang>
•Show 1‿3‿¯5 DotP 4‿¯2‿¯1</syntaxhighlight>
<lang bqn>3
<syntaxhighlight lang="bqn">3
3</lang>
3</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat> ( dot
<syntaxhighlight lang="bracmat"> ( dot
= a A z Z
= a A z Z
. !arg:(%?a ?z.%?A ?Z)
. !arg:(%?a ?z.%?A ?Z)
Line 598: Line 598:
| 0
| 0
)
)
& out$(dot$(1 3 -5.4 -2 -1));</lang>
& out$(dot$(1 3 -5.4 -2 -1));</syntaxhighlight>
{{out}}<pre>3</pre>
{{out}}<pre>3</pre>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>


Line 629: Line 629:


return sum;
return sum;
}</lang>
}</syntaxhighlight>
{{out}}<pre>3</pre>
{{out}}<pre>3</pre>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>static void Main(string[] args)
<syntaxhighlight lang="csharp">static void Main(string[] args)
{
{
Console.WriteLine(DotProduct(new decimal[] { 1, 3, -5 }, new decimal[] { 4, -2, -1 }));
Console.WriteLine(DotProduct(new decimal[] { 1, 3, -5 }, new decimal[] { 4, -2, -1 }));
Line 657: Line 657:


return tVal;
return tVal;
}</lang>
}</syntaxhighlight>
{{out}}<pre>3</pre>
{{out}}<pre>3</pre>


===Alternative using Linq (C# 4)===
===Alternative using Linq (C# 4)===
{{works with|C sharp|C#|4}}
{{works with|C sharp|C#|4}}
<lang csharp>public static decimal DotProduct(decimal[] a, decimal[] b) {
<syntaxhighlight lang="csharp">public static decimal DotProduct(decimal[] a, decimal[] b) {
return a.Zip(b, (x, y) => x * y).Sum();
return a.Zip(b, (x, y) => x * y).Sum();
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <numeric>
#include <numeric>


Line 678: Line 678:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}<pre>3</pre>
{{out}}<pre>3</pre>


===Alternative using std::valarray===
===Alternative using std::valarray===
<lang cpp>
<syntaxhighlight lang="cpp">
#include <valarray>
#include <valarray>
#include <iostream>
#include <iostream>
Line 696: Line 696:
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}<pre>3</pre>
{{out}}<pre>3</pre>


=== Alternative using std::inner_product ===
=== Alternative using std::inner_product ===
<lang cpp>
<syntaxhighlight lang="cpp">
#include <iostream>
#include <iostream>
#include <vector>
#include <vector>
Line 711: Line 711:
std::cout << "dot.product of {1,3,-5} and {4,-2,-1}: " << dp << std::endl;
std::cout << "dot.product of {1,3,-5} and {4,-2,-1}: " << dp << std::endl;
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}<pre>dot.product of {1,3,-5} and {4,-2,-1}: 3</pre>
{{out}}<pre>dot.product of {1,3,-5} and {4,-2,-1}: 3</pre>


Line 717: Line 717:
{{works with|Clojure|1.1}}
{{works with|Clojure|1.1}}
Preconditions are new in 1.1. The actual code also works in older Clojure versions.
Preconditions are new in 1.1. The actual code also works in older Clojure versions.
<lang clojure>(defn dot-product [& matrix]
<syntaxhighlight lang="clojure">(defn dot-product [& matrix]
{:pre [(apply == (map count matrix))]}
{:pre [(apply == (map count matrix))]}
(apply + (apply map * matrix)))
(apply + (apply map * matrix)))
Line 737: Line 737:
(println (dot-product2 [1 3 -5] [4 -2 -1]))
(println (dot-product2 [1 3 -5] [4 -2 -1]))
(println (dot-product3 [1 3 -5] [4 -2 -1]))
(println (dot-product3 [1 3 -5] [4 -2 -1]))
</syntaxhighlight>
</lang>


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>% Compute the dot product of two sequences
<syntaxhighlight lang="clu">% Compute the dot product of two sequences
% If the sequences are not the same length, it signals length_mismatch
% If the sequences are not the same length, it signals length_mismatch
% Any type may be used as long as it supports addition and multiplication
% Any type may be used as long as it supports addition and multiplication
Line 769: Line 769:


stream$putl(po, int$unparse(dot_product[int](a,b)))
stream$putl(po, int$unparse(dot_product[int](a,b)))
end start_up</lang>
end start_up</syntaxhighlight>
{{out}}
{{out}}
<pre>3</pre>
<pre>3</pre>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang coffeescript>dot_product = (ary1, ary2) ->
<syntaxhighlight lang="coffeescript">dot_product = (ary1, ary2) ->
if ary1.length != ary2.length
if ary1.length != ary2.length
throw "can't find dot product: arrays have different lengths"
throw "can't find dot product: arrays have different lengths"
Line 786: Line 786:
console.log dot_product([ 1, 3, -5 ], [ 4, -2, -1, 0 ]) # exception
console.log dot_product([ 1, 3, -5 ], [ 4, -2, -1, 0 ]) # exception
catch e
catch e
console.log e</lang>
console.log e</syntaxhighlight>
{{out}}<pre>> coffee foo.coffee
{{out}}<pre>> coffee foo.coffee
3
3
Line 792: Line 792:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun dot-product (a b)
<syntaxhighlight lang="lisp">(defun dot-product (a b)
(apply #'+ (mapcar #'* (coerce a 'list) (coerce b 'list))))</lang>
(apply #'+ (mapcar #'* (coerce a 'list) (coerce b 'list))))</syntaxhighlight>
This works with any size vector, and (as usual for Common Lisp) all numeric types (rationals, bignums, complex numbers, etc.).
This works with any size vector, and (as usual for Common Lisp) all numeric types (rationals, bignums, complex numbers, etc.).


Maybe it is better to do it without coercing. Then we got a cleaner code.
Maybe it is better to do it without coercing. Then we got a cleaner code.
<lang lisp>(defun dot-prod (a b)
<syntaxhighlight lang="lisp">(defun dot-prod (a b)
(reduce #'+ (map 'simple-vector #'* a b)))</lang>
(reduce #'+ (map 'simple-vector #'* a b)))</syntaxhighlight>


=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
{{Works with|BlackBox Component Builder}}
{{Works with|BlackBox Component Builder}}
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE DotProduct;
MODULE DotProduct;
IMPORT StdLog;
IMPORT StdLog;
Line 829: Line 829:


END DotProduct.
END DotProduct.
</syntaxhighlight>
</lang>
Execute: ^Q DotProduct.Test
Execute: ^Q DotProduct.Test
{{out}}
{{out}}
Line 837: Line 837:


=={{header|Cowgol}}==
=={{header|Cowgol}}==
<lang cowgol>include "cowgol.coh";
<syntaxhighlight lang="cowgol">include "cowgol.coh";


sub dotproduct(a: [int32], b: [int32], len: intptr): (n: int32) is
sub dotproduct(a: [int32], b: [int32], len: intptr): (n: int32) is
Line 861: Line 861:


printsgn(dotproduct(&A[0], &B[0], @sizeof A));
printsgn(dotproduct(&A[0], &B[0], @sizeof A));
print_nl();</lang>
print_nl();</syntaxhighlight>
{{out}}
{{out}}
<pre>3</pre>
<pre>3</pre>
Line 867: Line 867:
=={{header|Crystal}}==
=={{header|Crystal}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang ruby>class Vector
<syntaxhighlight lang="ruby">class Vector
property x, y, z
property x, y, z
Line 886: Line 886:
end
end


p [8, 13, -5].dot_product [4, -7, -11] # => -4</lang>
p [8, 13, -5].dot_product [4, -7, -11] # => -4</syntaxhighlight>


{{out}}<pre>3
{{out}}<pre>3
Line 892: Line 892:


=={{header|D}}==
=={{header|D}}==
<lang d>void main() {
<syntaxhighlight lang="d">void main() {
import std.stdio, std.numeric;
import std.stdio, std.numeric;


[1.0, 3.0, -5.0].dotProduct([4.0, -2.0, -1.0]).writeln;
[1.0, 3.0, -5.0].dotProduct([4.0, -2.0, -1.0]).writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>3</pre>
<pre>3</pre>
Using an array operation:
Using an array operation:
<lang d>void main() {
<syntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm;
import std.stdio, std.algorithm;


Line 907: Line 907:
double[3] c = a[] * b[];
double[3] c = a[] * b[];
c[].sum.writeln;
c[].sum.writeln;
}</lang>
}</syntaxhighlight>


=={{header|Dart}}==
=={{header|Dart}}==
<lang dart>num dot(List<num> A, List<num> B){
<syntaxhighlight lang="dart">num dot(List<num> A, List<num> B){
if (A.length != B.length){
if (A.length != B.length){
throw new Exception('Vectors must be of equal size');
throw new Exception('Vectors must be of equal size');
Line 925: Line 925:
var k = [4,-2,-1];
var k = [4,-2,-1];
print(dot(l,k));
print(dot(l,k));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>3</pre>
<pre>3</pre>
Line 931: Line 931:
=={{header|Delphi}}==
=={{header|Delphi}}==
{{works with|Lazarus}}
{{works with|Lazarus}}
<lang delphi>program Project1;
<syntaxhighlight lang="delphi">program Project1;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 957: Line 957:
WriteLn(DotProduct(x,y));
WriteLn(DotProduct(x,y));
ReadLn;
ReadLn;
end.</lang>
end.</syntaxhighlight>
{{out}}<pre> 3.00000000000000E+0000</pre>
{{out}}<pre> 3.00000000000000E+0000</pre>
Note: Delphi does not like arrays being declared in procedure headings, so it is necessary to declare it beforehand. To use integers, modify doublearray to be an array of integer.
Note: Delphi does not like arrays being declared in procedure headings, so it is necessary to declare it beforehand. To use integers, modify doublearray to be an array of integer.
Line 963: Line 963:
=={{header|DWScript}}==
=={{header|DWScript}}==
For arbitrary length vectors, using a precondition to check vector length:
For arbitrary length vectors, using a precondition to check vector length:
<lang delphi>function DotProduct(a, b : array of Float) : Float;
<syntaxhighlight lang="delphi">function DotProduct(a, b : array of Float) : Float;
require
require
a.Length = b.Length;
a.Length = b.Length;
Line 974: Line 974:
end;
end;


PrintLn(DotProduct([1,3,-5], [4,-2,-1]));</lang>
PrintLn(DotProduct([1,3,-5], [4,-2,-1]));</syntaxhighlight>
Using built-in 4D Vector type:
Using built-in 4D Vector type:
<lang delphi>var a := Vector(1, 3, -5, 0);
<syntaxhighlight lang="delphi">var a := Vector(1, 3, -5, 0);
var b := Vector(4, -2, -1, 0);
var b := Vector(4, -2, -1, 0);


PrintLn(a * b);</lang>
PrintLn(a * b);</syntaxhighlight>
Ouput in both cases:<pre>3</pre>
Ouput in both cases:<pre>3</pre>


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
<lang dejavu>dot a b:
<syntaxhighlight lang="dejavu">dot a b:
if /= len a len b:
if /= len a len b:
Raise value-error "dot product needs two vectors with the same length"
Raise value-error "dot product needs two vectors with the same length"
Line 991: Line 991:
+ * pop-from a pop-from b
+ * pop-from a pop-from b


!. dot [ 1 3 -5 ] [ 4 -2 -1 ]</lang>
!. dot [ 1 3 -5 ] [ 4 -2 -1 ]</syntaxhighlight>
{{out}}<pre>3</pre>
{{out}}<pre>3</pre>


=={{header|Draco}}==
=={{header|Draco}}==
<lang draco>proc nonrec dot_product([*] int a, b) int:
<syntaxhighlight lang="draco">proc nonrec dot_product([*] int a, b) int:
int total;
int total;
word i;
word i;
Line 1,009: Line 1,009:
[3] int b = (4, -2, -1);
[3] int b = (4, -2, -1);
write(dot_product(a, b))
write(dot_product(a, b))
corp</lang>
corp</syntaxhighlight>
{{out}}
{{out}}
<pre>3</pre>
<pre>3</pre>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang lisp>
<syntaxhighlight lang="lisp">
(define a #(1 3 -5))
(define a #(1 3 -5))
(define b #(4 -2 -1))
(define b #(4 -2 -1))
Line 1,025: Line 1,025:
(lib 'math)
(lib 'math)
(dot-product a b) → 3
(dot-product a b) → 3
</syntaxhighlight>
</lang>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
<lang Eiffel>class
<syntaxhighlight lang="eiffel">class
APPLICATION
APPLICATION


Line 1,061: Line 1,061:
end
end
end
end
end</lang>
end</syntaxhighlight>


Ouput:<pre>3</pre>
Ouput:<pre>3</pre>
Line 1,067: Line 1,067:
=={{header|Ela}}==
=={{header|Ela}}==
{{Trans|Haskell}}
{{Trans|Haskell}}
<lang ela>open list
<syntaxhighlight lang="ela">open list


dotp a b | length a == length b = sum (zipWith (*) a b)
dotp a b | length a == length b = sum (zipWith (*) a b)
| else = fail "Vector sizes must match."
| else = fail "Vector sizes must match."


dotp [1,3,-5] [4,-2,-1]</lang>
dotp [1,3,-5] [4,-2,-1]</syntaxhighlight>
{{out}}<pre>3</pre>
{{out}}<pre>3</pre>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0 :
ELENA 5.0 :
<lang elena>import extensions;
<syntaxhighlight lang="elena">import extensions;
import system'routines;
import system'routines;
Line 1,089: Line 1,089:
{
{
console.printLine(new int[]{1, 3, -5}.dotProduct(new int[]{4, -2, -1}))
console.printLine(new int[]{1, 3, -5}.dotProduct(new int[]{4, -2, -1}))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,097: Line 1,097:
=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Erlang}}
{{trans|Erlang}}
<lang elixir>defmodule Vector do
<syntaxhighlight lang="elixir">defmodule Vector do
def dot_product(a,b) when length(a)==length(b), do: dot_product(a,b,0)
def dot_product(a,b) when length(a)==length(b), do: dot_product(a,b,0)
def dot_product(_,_) do
def dot_product(_,_) do
Line 1,107: Line 1,107:
end
end


IO.puts Vector.dot_product([1,3,-5],[4,-2,-1])</lang>
IO.puts Vector.dot_product([1,3,-5],[4,-2,-1])</syntaxhighlight>


{{out}}
{{out}}
Line 1,116: Line 1,116:
=={{header|Elm}}==
=={{header|Elm}}==
{{trans|Elm}}
{{trans|Elm}}
<lang Elm>dotp: List number -> List number -> Maybe number
<syntaxhighlight lang="elm">dotp: List number -> List number -> Maybe number
dotp a b =
dotp a b =
if List.length a /= List.length b then
if List.length a /= List.length b then
Line 1,123: Line 1,123:
Just (List.sum <| List.map2 (*) a b)
Just (List.sum <| List.map2 (*) a b)


dotp [1,3,-5] [4,-2,-1])</lang>
dotp [1,3,-5] [4,-2,-1])</syntaxhighlight>


{{out}}
{{out}}
Line 1,131: Line 1,131:


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<lang Lisp>(defun dot-product (v1 v2)
<syntaxhighlight lang="lisp">(defun dot-product (v1 v2)
(let ((res 0))
(let ((res 0))
(dotimes (i (length v1))
(dotimes (i (length v1))
Line 1,138: Line 1,138:


(dot-product [1 2 3] [1 2 3]) ;=> 14
(dot-product [1 2 3] [1 2 3]) ;=> 14
(dot-product '(1 2 3) '(1 2 3)) ;=> 14</lang>
(dot-product '(1 2 3) '(1 2 3)) ;=> 14</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>dotProduct(A,B) when length(A) == length(B) -> dotProduct(A,B,0);
<syntaxhighlight lang="erlang">dotProduct(A,B) when length(A) == length(B) -> dotProduct(A,B,0);
dotProduct(_,_) -> erlang:error('Vectors must have the same length.').
dotProduct(_,_) -> erlang:error('Vectors must have the same length.').


Line 1,147: Line 1,147:
dotProduct([],[],P) -> P.
dotProduct([],[],P) -> P.


dotProduct([1,3,-5],[4,-2,-1]).</lang>
dotProduct([1,3,-5],[4,-2,-1]).</syntaxhighlight>
{{out}}<pre>3</pre>
{{out}}<pre>3</pre>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang Euphoria>function dotprod(sequence a, sequence b)
<syntaxhighlight lang="euphoria">function dotprod(sequence a, sequence b)
atom sum
atom sum
a *= b
a *= b
Line 1,161: Line 1,161:
end function
end function


? dotprod({1,3,-5},{4,-2,-1})</lang>
? dotprod({1,3,-5},{4,-2,-1})</syntaxhighlight>
{{out}}
{{out}}
<pre>3</pre>
<pre>3</pre>
<lang Euphoria>-- Here is an alternative method,
<syntaxhighlight lang="euphoria">-- Here is an alternative method,
-- using the standard Euphoria Version 4+ Math Library
-- using the standard Euphoria Version 4+ Math Library
include std/math.e
include std/math.e
sequence a = {1,3,-5}, b = {4,-2,-1} -- Make them any length you want
sequence a = {1,3,-5}, b = {4,-2,-1} -- Make them any length you want
? sum(a * b)</lang>
? sum(a * b)</syntaxhighlight>
{{out}}<pre>3</pre>
{{out}}<pre>3</pre>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>let dot_product (a:array<'a>) (b:array<'a>) =
<syntaxhighlight lang="fsharp">let dot_product (a:array<'a>) (b:array<'a>) =
if Array.length a <> Array.length b then failwith "invalid argument: vectors must have the same lengths"
if Array.length a <> Array.length b then failwith "invalid argument: vectors must have the same lengths"
Array.fold2 (fun acc i j -> acc + (i * j)) 0 a b</lang>
Array.fold2 (fun acc i j -> acc + (i * j)) 0 a b</syntaxhighlight>
<pre>&gt; dot_product [| 1; 3; -5 |] [| 4; -2; -1 |] ;;
<pre>&gt; dot_product [| 1; 3; -5 |] [| 4; -2; -1 |] ;;
val it : int = 3</pre>
val it : int = 3</pre>
Line 1,180: Line 1,180:
=={{header|Factor}}==
=={{header|Factor}}==
The built-in word <code>v.</code> is used to compute the dot product. It doesn't enforce that the vectors are of the same length, so here's a wrapper.
The built-in word <code>v.</code> is used to compute the dot product. It doesn't enforce that the vectors are of the same length, so here's a wrapper.
<lang factor>USING: kernel math.vectors sequences ;
<syntaxhighlight lang="factor">USING: kernel math.vectors sequences ;


: dot-product ( u v -- w )
: dot-product ( u v -- w )
2dup [ length ] bi@ =
2dup [ length ] bi@ =
[ v. ] [ "Vector lengths must be equal" throw ] if ;</lang>
[ v. ] [ "Vector lengths must be equal" throw ] if ;</syntaxhighlight>


( scratchpad ) { 1 3 -5 } { 4 -2 -1 } dot-product .
( scratchpad ) { 1 3 -5 } { 4 -2 -1 } dot-product .
Line 1,190: Line 1,190:


=={{header|FALSE}}==
=={{header|FALSE}}==
<lang false>[[\1-$0=~][$d;2*1+\-ø\$d;2+\-ø@*@+]#]p:
<syntaxhighlight lang="false">[[\1-$0=~][$d;2*1+\-ø\$d;2+\-ø@*@+]#]p:
3d: {Vectors' length}
3d: {Vectors' length}
1 3 5_ 4 2_ 1_ d;$1+ø@*p;!%. {Output: 3}</lang>
1 3 5_ 4 2_ 1_ d;$1+ø@*p;!%. {Output: 3}</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==
Dot product of lists of Int:
Dot product of lists of Int:
<lang fantom>class DotProduct
<syntaxhighlight lang="fantom">class DotProduct
{
{
static Int dotProduct (Int[] a, Int[] b)
static Int dotProduct (Int[] a, Int[] b)
Line 1,215: Line 1,215:
echo ("Dot product of $x and $y is ${dotProduct(x, y)}")
echo ("Dot product of $x and $y is ${dotProduct(x, y)}")
}
}
}</lang>
}</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>: vector create cells allot ;
<syntaxhighlight lang="forth">: vector create cells allot ;
: th cells + ;
: th cells + ;


Line 1,234: Line 1,234:
-1 -2 4 b /vector vector!
-1 -2 4 b /vector vector!


a b /vector dotproduct . 3 ok</lang>
a b /vector dotproduct . 3 ok</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==


<lang fortran>program test_dot_product
<syntaxhighlight lang="fortran">program test_dot_product


write (*, '(i0)') dot_product ([1, 3, -5], [4, -2, -1])
write (*, '(i0)') dot_product ([1, 3, -5], [4, -2, -1])


end program test_dot_product</lang>
end program test_dot_product</syntaxhighlight>
{{out}}<pre>3</pre>
{{out}}<pre>3</pre>


Line 1,248: Line 1,248:


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>dotProduct[v1, v2] :=
<syntaxhighlight lang="frink">dotProduct[v1, v2] :=
{
{
if length[v1] != length[v2]
if length[v1] != length[v2]
Line 1,257: Line 1,257:
return sum[map[{|c1,c2| c1 * c2}, zip[v1, v2]]]
return sum[map[{|c1,c2| c1 * c2}, zip[v1, v2]]]
}</lang>
}</syntaxhighlight>


=={{header|FunL}}==
=={{header|FunL}}==
<lang funl>import lists.zipWith
<syntaxhighlight lang="funl">import lists.zipWith


def dot( a, b )
def dot( a, b )
Line 1,266: Line 1,266:
| otherwise = error( "Vector sizes must match" )
| otherwise = error( "Vector sizes must match" )


println( dot([1, 3, -5], [4, -2, -1]) )</lang>
println( dot([1, 3, -5], [4, -2, -1]) )</syntaxhighlight>
{{out}}<pre>3</pre>
{{out}}<pre>3</pre>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>#define NAN 0.0/0.0 'dot product of different-dimensioned vectors is no more defined than 0/0
<syntaxhighlight lang="freebasic">#define NAN 0.0/0.0 'dot product of different-dimensioned vectors is no more defined than 0/0


function dot( a() as double, b() as double ) as double
function dot( a() as double, b() as double ) as double
Line 1,294: Line 1,294:
print " zero3d dot x = ", dot(zero3d(), x())
print " zero3d dot x = ", dot(zero3d(), x())
print " z dot z = ", dot(z(), z())
print " z dot z = ", dot(z(), z())
print " y dot z = ", dot(y(), z())</lang>
print " y dot z = ", dot(y(), z())</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,312: Line 1,312:


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap># Built-in
<syntaxhighlight lang="gap"># Built-in


[1, 3, -5]*[4, -2, -1];
[1, 3, -5]*[4, -2, -1];
# 3</lang>
# 3</syntaxhighlight>


=={{header|GLSL}}==
=={{header|GLSL}}==
The dot product is built-in:
The dot product is built-in:
<lang glsl>
<syntaxhighlight lang="glsl">
float dot_product = dot(vec3(1, 3, -5), vec3(4, -2, -1));
float dot_product = dot(vec3(1, 3, -5), vec3(4, -2, -1));
</syntaxhighlight>
</lang>


=={{header|Go}}==
=={{header|Go}}==
===Implementation===
===Implementation===
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,354: Line 1,354:
}
}
fmt.Println(d)
fmt.Println(d)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,360: Line 1,360:
</pre>
</pre>
===Library gonum/floats===
===Library gonum/floats===
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,375: Line 1,375:
func main() {
func main() {
fmt.Println(floats.Dot(v1, v2))
fmt.Println(floats.Dot(v1, v2))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,383: Line 1,383:
=={{header|Groovy}}==
=={{header|Groovy}}==
Solution:
Solution:
<lang groovy>def dotProduct = { x, y ->
<syntaxhighlight lang="groovy">def dotProduct = { x, y ->
assert x && y && x.size() == y.size()
assert x && y && x.size() == y.size()
[x, y].transpose().collect{ xx, yy -> xx * yy }.sum()
[x, y].transpose().collect{ xx, yy -> xx * yy }.sum()
}</lang>
}</syntaxhighlight>
Test:
Test:
<lang groovy>println dotProduct([1, 3, -5], [4, -2, -1])</lang>
<syntaxhighlight lang="groovy">println dotProduct([1, 3, -5], [4, -2, -1])</syntaxhighlight>
{{out}}<pre>3</pre>
{{out}}<pre>3</pre>


=={{header|Haskell}}==
=={{header|Haskell}}==


<lang haskell>dotp :: Num a => [a] -> [a] -> a
<syntaxhighlight lang="haskell">dotp :: Num a => [a] -> [a] -> a
dotp a b | length a == length b = sum (zipWith (*) a b)
dotp a b | length a == length b = sum (zipWith (*) a b)
| otherwise = error "Vector sizes must match"
| otherwise = error "Vector sizes must match"
main = print $ dotp [1, 3, -5] [4, -2, -1] -- prints 3</lang>
main = print $ dotp [1, 3, -5] [4, -2, -1] -- prints 3</syntaxhighlight>


Or, using the Maybe monad to avoid exceptions and keep things composable:
Or, using the Maybe monad to avoid exceptions and keep things composable:
<lang haskell>dotp
<syntaxhighlight lang="haskell">dotp
:: Num a
:: Num a
=> [a] -> [a] -> Maybe a
=> [a] -> [a] -> Maybe a
Line 1,414: Line 1,414:
=> Maybe a -> IO ()
=> Maybe a -> IO ()
mbPrint (Just x) = print x
mbPrint (Just x) = print x
mbPrint n = print n</lang>
mbPrint n = print n</syntaxhighlight>


=={{header|Hoon}}==
=={{header|Hoon}}==
<lang hoon>|= [a=(list @sd) b=(list @sd)]
<syntaxhighlight lang="hoon">|= [a=(list @sd) b=(list @sd)]
=| sum=@sd
=| sum=@sd
|-
|-
?: |(?=(~ a) ?=(~ b)) sum
?: |(?=(~ a) ?=(~ b)) sum
$(a t.a, b t.b, sum (sum:si sum (pro:si i.a i.b)))</lang>
$(a t.a, b t.b, sum (sum:si sum (pro:si i.a i.b)))</syntaxhighlight>


=={{header|Hy}}==
=={{header|Hy}}==
<lang clojure>(defn dotp [a b]
<syntaxhighlight lang="clojure">(defn dotp [a b]
(assert (= (len a) (len b)))
(assert (= (len a) (len b)))
(sum (genexpr (* aterm bterm)
(sum (genexpr (* aterm bterm)
[(, aterm bterm) (zip a b)])))
[(, aterm bterm) (zip a b)])))


(assert (= 3 (dotp [1 3 -5] [4 -2 -1])))</lang>
(assert (= 3 (dotp [1 3 -5] [4 -2 -1])))</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
The procedure below computes the dot product of two vectors of arbitrary length or generates a run time error if its arguments are the wrong type or shape.
The procedure below computes the dot product of two vectors of arbitrary length or generates a run time error if its arguments are the wrong type or shape.
<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
write("a dot b := ",dotproduct([1, 3, -5],[4, -2, -1]))
write("a dot b := ",dotproduct([1, 3, -5],[4, -2, -1]))
end
end
Line 1,441: Line 1,441:
every (dp := 0) +:= a[i := 1 to *a] * b[i]
every (dp := 0) +:= a[i := 1 to *a] * b[i]
return dp
return dp
end</lang>
end</syntaxhighlight>


=={{header|IDL}}==
=={{header|IDL}}==
<syntaxhighlight lang="idl">
<lang IDL>
a = [1, 3, -5]
a = [1, 3, -5]
b = [4, -2, -1]
b = [4, -2, -1]
c = a#TRANSPOSE(b)
c = a#TRANSPOSE(b)
c = TOTAL(a*b,/PRESERVE_TYPE)
c = TOTAL(a*b,/PRESERVE_TYPE)
</syntaxhighlight>
</lang>


=={{header|Idris}}==
=={{header|Idris}}==
<lang idris>module Main
<syntaxhighlight lang="idris">module Main


import Data.Vect
import Data.Vect
Line 1,461: Line 1,461:
main : IO ()
main : IO ()
main = printLn $ dotProduct [1,2,3] [1,2,3]
main = printLn $ dotProduct [1,2,3] [1,2,3]
</syntaxhighlight>
</lang>


=={{header|J}}==
=={{header|J}}==
<lang j> 1 3 _5 +/ . * 4 _2 _1
<syntaxhighlight lang="j"> 1 3 _5 +/ . * 4 _2 _1
3
3
dotp=: +/ . * NB. Or defined as a verb (function)
dotp=: +/ . * NB. Or defined as a verb (function)
1 3 _5 dotp 4 _2 _1
1 3 _5 dotp 4 _2 _1
3</lang>
3</syntaxhighlight>
Note also: The verbs built using the conjunction <code> .</code> generally apply to matricies and arrays of higher dimensions and can be built with verbs (functions) other than sum ( <code>+/</code> ) and product ( <code>*</code> ).
Note also: The verbs built using the conjunction <code> .</code> generally apply to matricies and arrays of higher dimensions and can be built with verbs (functions) other than sum ( <code>+/</code> ) and product ( <code>*</code> ).


Line 1,474: Line 1,474:


=={{header|Java}}==
=={{header|Java}}==
<lang java>public class DotProduct {
<syntaxhighlight lang="java">public class DotProduct {
public static void main(String[] args) {
public static void main(String[] args) {
Line 1,493: Line 1,493:
return sum;
return sum;
}
}
}</lang>
}</syntaxhighlight>
{{out}}<pre>3.0</pre>
{{out}}<pre>3.0</pre>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
===ES5===
===ES5===
<lang javascript>function dot_product(ary1, ary2) {
<syntaxhighlight lang="javascript">function dot_product(ary1, ary2) {
if (ary1.length != ary2.length)
if (ary1.length != ary2.length)
throw "can't find dot product: arrays have different lengths";
throw "can't find dot product: arrays have different lengths";
Line 1,508: Line 1,508:


print(dot_product([1,3,-5],[4,-2,-1])); // ==> 3
print(dot_product([1,3,-5],[4,-2,-1])); // ==> 3
print(dot_product([1,3,-5],[4,-2,-1,0])); // ==> exception</lang>
print(dot_product([1,3,-5],[4,-2,-1,0])); // ==> exception</syntaxhighlight>


We could also use map and reduce in lieu of iteration,
We could also use map and reduce in lieu of iteration,


<lang javascript>function dotp(x,y) {
<syntaxhighlight lang="javascript">function dotp(x,y) {
function dotp_sum(a,b) { return a + b; }
function dotp_sum(a,b) { return a + b; }
function dotp_times(a,i) { return x[i] * y[i]; }
function dotp_times(a,i) { return x[i] * y[i]; }
Line 1,521: Line 1,521:


dotp([1,3,-5],[4,-2,-1]); // ==> 3
dotp([1,3,-5],[4,-2,-1]); // ==> 3
dotp([1,3,-5],[4,-2,-1,0]); // ==> exception</lang>
dotp([1,3,-5],[4,-2,-1,0]); // ==> exception</syntaxhighlight>


===ES6===
===ES6===
Composing functional primitives into a '''dotProduct()''' which returns '''undefined''' (rather than an error) when the array lengths are unmatched.
Composing functional primitives into a '''dotProduct()''' which returns '''undefined''' (rather than an error) when the array lengths are unmatched.


<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
'use strict';


Line 1,546: Line 1,546:


return dotProduct([1, 3, -5], [4, -2, -1]);
return dotProduct([1, 3, -5], [4, -2, -1]);
})();</lang>
})();</syntaxhighlight>


{{Out}}
{{Out}}
<syntaxhighlight lang="javascript">3</syntaxhighlight>
<lang JavaScript>3</lang>


=={{header|jq}}==
=={{header|jq}}==
The dot-product of two arrays, x and y, can be computed using dot(x;y) defined as follows:
The dot-product of two arrays, x and y, can be computed using dot(x;y) defined as follows:
<syntaxhighlight lang="jq">
<lang jq>
def dot(x; y):
def dot(x; y):
reduce range(0;x|length) as $i (0; . + x[$i] * y[$i]);
reduce range(0;x|length) as $i (0; . + x[$i] * y[$i]);
</syntaxhighlight>
</lang>


Suppose however that we are given an array of objects, each of which has an "x" field and a "y" field,
Suppose however that we are given an array of objects, each of which has an "x" field and a "y" field,
Line 1,562: Line 1,562:
values in the "x" and "y" fields respectively.
values in the "x" and "y" fields respectively.


This can most usefully be accomplished in jq with the aid of SIGMA(f) defined as follows:<lang jq>def SIGMA( f ): reduce .[] as $o (0; . + ($o | f )) ;</lang>
This can most usefully be accomplished in jq with the aid of SIGMA(f) defined as follows:<syntaxhighlight lang="jq">def SIGMA( f ): reduce .[] as $o (0; . + ($o | f )) ;</syntaxhighlight>
Given the array of objects as input, the dot-product is then simply <code>SIGMA( .x * .y )</code>.
Given the array of objects as input, the dot-product is then simply <code>SIGMA( .x * .y )</code>.


Example:<lang jq>dot( [1, 3, -5]; [4, -2, -1]) # => 3
Example:<syntaxhighlight lang="jq">dot( [1, 3, -5]; [4, -2, -1]) # => 3


[ {"x": 1, "y": 4}, {"x": 3, "y": -2}, {"x": -5, "y": -1} ]
[ {"x": 1, "y": 4}, {"x": 3, "y": -2}, {"x": -5, "y": -1} ]
| SIGMA( .x * .y ) # => 3</lang>
| SIGMA( .x * .y ) # => 3</syntaxhighlight>


=={{header|Jsish}}==
=={{header|Jsish}}==
From Javascript ES5 imperative entry.
From Javascript ES5 imperative entry.
<lang javascript>/* Dot product, in Jsish */
<syntaxhighlight lang="javascript">/* Dot product, in Jsish */
function dot_product(ary1, ary2) {
function dot_product(ary1, ary2) {
if (ary1.length != ary2.length) throw "can't find dot product: arrays have different lengths";
if (ary1.length != ary2.length) throw "can't find dot product: arrays have different lengths";
Line 1,589: Line 1,589:
PASS!: err = can't find dot product: arrays have different lengths
PASS!: err = can't find dot product: arrays have different lengths
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>


{{out}}
{{out}}
Line 1,602: Line 1,602:
=={{header|Julia}}==
=={{header|Julia}}==
Dot products and many other linear-algebra functions are built-in functions in Julia (and are largely implemented by calling functions from [[wp:LAPACK|LAPACK]]).
Dot products and many other linear-algebra functions are built-in functions in Julia (and are largely implemented by calling functions from [[wp:LAPACK|LAPACK]]).
<lang julia>x = [1, 3, -5]
<syntaxhighlight lang="julia">x = [1, 3, -5]
y = [4, -2, -1]
y = [4, -2, -1]
z = dot(x, y)
z = dot(x, y)
z = x'*y
z = x'*y
z = x ⋅ y</lang>
z = x ⋅ y</syntaxhighlight>


=={{header|K}}==
=={{header|K}}==
<lang K> +/1 3 -5 * 4 -2 -1
<syntaxhighlight lang="k"> +/1 3 -5 * 4 -2 -1
3
3


1 3 -5 _dot 4 -2 -1
1 3 -5 _dot 4 -2 -1
3</lang>
3</syntaxhighlight>


=={{header|Klingphix}}==
=={{header|Klingphix}}==
<lang>:sq_mul
<syntaxhighlight lang="text">:sq_mul
%c %i
%c %i
( ) !c
( ) !c
Line 1,639: Line 1,639:
pstack
pstack


" " input</lang>
" " input</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{works with|Kotlin|1.0+}}
{{works with|Kotlin|1.0+}}
<lang scala>fun dot(v1: Array<Double>, v2: Array<Double>) =
<syntaxhighlight lang="scala">fun dot(v1: Array<Double>, v2: Array<Double>) =
v1.zip(v2).map { it.first * it.second }.reduce { a, b -> a + b }
v1.zip(v2).map { it.first * it.second }.reduce { a, b -> a + b }


fun main(args: Array<String>) {
fun main(args: Array<String>) {
dot(arrayOf(1.0, 3.0, -5.0), arrayOf(4.0, -2.0, -1.0)).let { println(it) }
dot(arrayOf(1.0, 3.0, -5.0), arrayOf(4.0, -2.0, -1.0)).let { println(it) }
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>3.0</pre>
<pre>3.0</pre>


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang="scheme">
{def dotp
{def dotp
{def dotp.r
{def dotp.r
Line 1,672: Line 1,672:
{dotp {A.new 1 3 -5} {A.new 4 -2 -1}}
{dotp {A.new 1 3 -5} {A.new 4 -2 -1}}
-> 3
-> 3
</syntaxhighlight>
</lang>


=={{header|LFE}}==
=={{header|LFE}}==
<lang lisp>(defun dot-product (a b)
<syntaxhighlight lang="lisp">(defun dot-product (a b)
(: lists foldl #'+/2 0
(: lists foldl #'+/2 0
(: lists zipwith #'*/2 a b)))
(: lists zipwith #'*/2 a b)))
</syntaxhighlight>
</lang>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>vectorA$ = "1, 3, -5"
<syntaxhighlight lang="lb">vectorA$ = "1, 3, -5"
vectorB$ = "4, -2, -1"
vectorB$ = "4, -2, -1"
print "DotProduct of ";vectorA$;" and "; vectorB$;" is ";
print "DotProduct of ";vectorA$;" and "; vectorB$;" is ";
Line 1,704: Line 1,704:
i = i+1
i = i+1
wend
wend
end function </lang>
end function </syntaxhighlight>


=={{header|LLVM}}==
=={{header|LLVM}}==
<lang llvm>; This is not strictly LLVM, as it uses the C library function "printf".
<syntaxhighlight lang="llvm">; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.
; to just load the string into memory, and that would be boring.
Line 1,791: Line 1,791:
declare void @llvm.memcpy.p0i8.p0i8.i64(i8* nocapture writeonly, i8* nocapture readonly, i64, i32, i1) #1
declare void @llvm.memcpy.p0i8.p0i8.i64(i8* nocapture writeonly, i8* nocapture readonly, i64, i32, i1) #1


attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }</lang>
attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }</syntaxhighlight>
{{out}}
{{out}}
<pre>3</pre>
<pre>3</pre>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>to dotprod :a :b
<syntaxhighlight lang="logo">to dotprod :a :b
output apply "sum (map "product :a :b)
output apply "sum (map "product :a :b)
end
end


show dotprod [1 3 -5] [4 -2 -1] ; 3</lang>
show dotprod [1 3 -5] [4 -2 -1] ; 3</syntaxhighlight>


=={{header|Logtalk}}==
=={{header|Logtalk}}==
<lang logtalk>dot_product(A, B, Sum) :-
<syntaxhighlight lang="logtalk">dot_product(A, B, Sum) :-
dot_product(A, B, 0, Sum).
dot_product(A, B, 0, Sum).


Line 1,809: Line 1,809:
dot_product([A| As], [B| Bs], Acc, Sum) :-
dot_product([A| As], [B| Bs], Acc, Sum) :-
Acc2 is Acc + A*B,
Acc2 is Acc + A*B,
dot_product(As, Bs, Acc2, Sum).</lang>
dot_product(As, Bs, Acc2, Sum).</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>function dotprod(a, b)
<syntaxhighlight lang="lua">function dotprod(a, b)
local ret = 0
local ret = 0
for i = 1, #a do
for i = 1, #a do
Line 1,820: Line 1,820:
end
end


print(dotprod({1, 3, -5}, {4, -2, 1}))</lang>
print(dotprod({1, 3, -5}, {4, -2, 1}))</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module dot_product {
Module dot_product {
A=(1,3,-5)
A=(1,3,-5)
Line 1,838: Line 1,838:
}
}
Module dot_product
Module dot_product
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
Between Arrays, Vectors, or Matrices you can use the dot operator:
Between Arrays, Vectors, or Matrices you can use the dot operator:
<lang Maple><1,2,3> . <4,5,6></lang>
<syntaxhighlight lang="maple"><1,2,3> . <4,5,6></syntaxhighlight>
<lang Maple>Array([1,2,3]) . Array([4,5,6])</lang>
<syntaxhighlight lang="maple">Array([1,2,3]) . Array([4,5,6])</syntaxhighlight>


Between any of the above or lists, you can use the <code>LinearAlgebra[DotProduct]</code> function:
Between any of the above or lists, you can use the <code>LinearAlgebra[DotProduct]</code> function:
<lang Maple>LinearAlgebra( <1,2,3>, <4,5,6> )</lang>
<syntaxhighlight lang="maple">LinearAlgebra( <1,2,3>, <4,5,6> )</syntaxhighlight>
<lang Maple>LinearAlgebra( Array([1,2,3]), Array([4,5,6]) )</lang>
<syntaxhighlight lang="maple">LinearAlgebra( Array([1,2,3]), Array([4,5,6]) )</syntaxhighlight>
<lang Maple>LinearAlgebra([1,2,3], [4,5,6] )</lang>
<syntaxhighlight lang="maple">LinearAlgebra([1,2,3], [4,5,6] )</syntaxhighlight>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>{1,3,-5}.{4,-2,-1}</lang>
<syntaxhighlight lang="mathematica">{1,3,-5}.{4,-2,-1}</syntaxhighlight>


=={{header|MATLAB}}==
=={{header|MATLAB}}==
The dot product operation is a built-in function that operates on vectors of arbitrary length.
The dot product operation is a built-in function that operates on vectors of arbitrary length.
<lang matlab>A = [1 3 -5]
<syntaxhighlight lang="matlab">A = [1 3 -5]
B = [4 -2 -1]
B = [4 -2 -1]
C = dot(A,B)</lang>
C = dot(A,B)</syntaxhighlight>
For the Octave implimentation:
For the Octave implimentation:
<lang matlab>function C = DotPro(A,B)
<syntaxhighlight lang="matlab">function C = DotPro(A,B)
C = sum( A.*B );
C = sum( A.*B );
end</lang>
end</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>[1, 3, -5] . [4, -2, -1];
<syntaxhighlight lang="maxima">[1, 3, -5] . [4, -2, -1];
/* 3 */</lang>
/* 3 */</syntaxhighlight>


=={{header|Mercury}}==
=={{header|Mercury}}==
This will cause a software_error/1 exception if the lists are of different lengths.
This will cause a software_error/1 exception if the lists are of different lengths.
<lang mercury>:- module dot_product.
<syntaxhighlight lang="mercury">:- module dot_product.
:- interface.
:- interface.


Line 1,885: Line 1,885:


dot_product(As, Bs) =
dot_product(As, Bs) =
list.foldl_corresponding((func(A, B, Acc) = Acc + A * B), As, Bs, 0).</lang>
list.foldl_corresponding((func(A, B, Acc) = Acc + A * B), As, Bs, 0).</syntaxhighlight>


=={{header|МК-61/52}}==
=={{header|МК-61/52}}==
<lang>С/П * ИП0 + П0 С/П БП 00</lang>
<syntaxhighlight lang="text">С/П * ИП0 + П0 С/П БП 00</syntaxhighlight>


''Input'': В/О x<sub>1</sub> С/П x<sub>2</sub> С/П y<sub>1</sub> С/П y<sub>2</sub> С/П ...
''Input'': В/О x<sub>1</sub> С/П x<sub>2</sub> С/П y<sub>1</sub> С/П y<sub>2</sub> С/П ...


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE DotProduct;
<syntaxhighlight lang="modula2">MODULE DotProduct;
FROM RealStr IMPORT RealToStr;
FROM RealStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 1,917: Line 1,917:


ReadChar
ReadChar
END DotProduct.</lang>
END DotProduct.</syntaxhighlight>


=={{header|MUMPS}}==
=={{header|MUMPS}}==
<lang MUMPS>DOTPROD(A,B)
<syntaxhighlight lang="mumps">DOTPROD(A,B)
;Returns the dot product of two vectors. Vectors are assumed to be stored as caret-delimited strings of numbers.
;Returns the dot product of two vectors. Vectors are assumed to be stored as caret-delimited strings of numbers.
;If the vectors are not of equal length, a null string is returned.
;If the vectors are not of equal length, a null string is returned.
Line 1,928: Line 1,928:
FOR I=1:1:$LENGTH(A,"^") SET SUM=SUM+($PIECE(A,"^",I)*$PIECE(B,"^",I))
FOR I=1:1:$LENGTH(A,"^") SET SUM=SUM+($PIECE(A,"^",I)*$PIECE(B,"^",I))
KILL I
KILL I
QUIT SUM</lang>
QUIT SUM</syntaxhighlight>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
This will cause an exception if the arrays are different lengths.
This will cause an exception if the arrays are different lengths.
<lang Nemerle>using System;
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using System.Console;
using Nemerle.Collections.NCollectionsExtensions;
using Nemerle.Collections.NCollectionsExtensions;
Line 1,948: Line 1,948:
WriteLine(DotProduct(arr1, arr2));
WriteLine(DotProduct(arr1, arr2));
}
}
}</lang>
}</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols binary
options replace format comments java crossref savelog symbols binary


Line 1,971: Line 1,971:


method dotProduct(vecs = double[,]) public constant returns double signals IllegalArgumentException
method dotProduct(vecs = double[,]) public constant returns double signals IllegalArgumentException
return dotProduct(vecs[0], vecs[1])</lang>
return dotProduct(vecs[0], vecs[1])</syntaxhighlight>


=={{header|newLISP}}==
=={{header|newLISP}}==
<lang newLISP>(define (dot-product x y)
<syntaxhighlight lang="newlisp">(define (dot-product x y)
(apply + (map * x y)))
(apply + (map * x y)))


(println (dot-product '(1 3 -5) '(4 -2 -1)))</lang>
(println (dot-product '(1 3 -5) '(4 -2 -1)))</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim># Compile time error when a and b are differently sized arrays
<syntaxhighlight lang="nim"># Compile time error when a and b are differently sized arrays
# Runtime error when a and b are differently sized seqs
# Runtime error when a and b are differently sized seqs
proc dotp[T](a,b: T): int =
proc dotp[T](a,b: T): int =
Line 1,988: Line 1,988:


echo dotp([1,3,-5], [4,-2,-1])
echo dotp([1,3,-5], [4,-2,-1])
echo dotp(@[1,2,3],@[4,5,6])</lang>
echo dotp(@[1,2,3],@[4,5,6])</syntaxhighlight>


Another version which allows to mix arrays and sequences provided they have the same length. It works also with miscellaneous number types (integers, floats).
Another version which allows to mix arrays and sequences provided they have the same length. It works also with miscellaneous number types (integers, floats).


<lang Nim># Runtime error if lengths of arrays or sequences differ.
<syntaxhighlight lang="nim"># Runtime error if lengths of arrays or sequences differ.


func dotProduct[T](a, b: openArray[T]): T =
func dotProduct[T](a, b: openArray[T]): T =
Line 2,001: Line 2,001:
echo dotProduct([1,3,-5], [4,-2,-1])
echo dotProduct([1,3,-5], [4,-2,-1])
echo dotProduct(@[1,2,3],@[4,5,6])
echo dotProduct(@[1,2,3],@[4,5,6])
echo dotProduct([1.0, 2.0, 3.0], @[7.0, 8.0, 9.0])</lang>
echo dotProduct([1.0, 2.0, 3.0], @[7.0, 8.0, 9.0])</syntaxhighlight>


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
{{Works with|oo2c version 2}}
{{Works with|oo2c version 2}}
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE DotProduct;
MODULE DotProduct;
IMPORT
IMPORT
Line 2,031: Line 2,031:
Out.Int(DotProduct(x,y),0);Out.Ln
Out.Int(DotProduct(x,y),0);Out.Ln
END DotProduct.
END DotProduct.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,038: Line 2,038:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>bundle Default {
<syntaxhighlight lang="objeck">bundle Default {
class DotProduct {
class DotProduct {
function : Main(args : String[]) ~ Nil {
function : Main(args : String[]) ~ Nil {
Line 2,065: Line 2,065:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
<lang objc>#import <stdio.h>
<syntaxhighlight lang="objc">#import <stdio.h>
#import <stdint.h>
#import <stdint.h>
#import <stdlib.h>
#import <stdlib.h>
Line 2,174: Line 2,174:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
With lists:
With lists:
<lang ocaml>let dot = List.fold_left2 (fun z x y -> z +. x *. y) 0.
<syntaxhighlight lang="ocaml">let dot = List.fold_left2 (fun z x y -> z +. x *. y) 0.


(*
(*
# dot [1.0; 3.0; -5.0] [4.0; -2.0; -1.0];;
# dot [1.0; 3.0; -5.0] [4.0; -2.0; -1.0];;
- : float = 3.
- : float = 3.
*)</lang>
*)</syntaxhighlight>


With arrays:
With arrays:
<lang ocaml>let dot v u =
<syntaxhighlight lang="ocaml">let dot v u =
if Array.length v <> Array.length u
if Array.length v <> Array.length u
then invalid_arg "Different array lengths";
then invalid_arg "Different array lengths";
Line 2,196: Line 2,196:
# dot [| 1.0; 3.0; -5.0 |] [| 4.0; -2.0; -1.0 |];;
# dot [| 1.0; 3.0; -5.0 |] [| 4.0; -2.0; -1.0 |];;
- : float = 3.
- : float = 3.
*)</lang>
*)</syntaxhighlight>


=={{header|Octave}}==
=={{header|Octave}}==
See [[Dot product#MATLAB]] for an implementation. If we have a row-vector and a column-vector, we can use simply *.
See [[Dot product#MATLAB]] for an implementation. If we have a row-vector and a column-vector, we can use simply *.
<lang octave>a = [1, 3, -5]
<syntaxhighlight lang="octave">a = [1, 3, -5]
b = [4, -2, -1] % or [4; -2; -1] and avoid transposition with '
b = [4, -2, -1] % or [4; -2; -1] and avoid transposition with '
disp( a * b' ) % ' means transpose</lang>
disp( a * b' ) % ' means transpose</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>: dotProduct zipWith(#*) sum ;</lang>
<syntaxhighlight lang="oforth">: dotProduct zipWith(#*) sum ;</syntaxhighlight>


{{out}}
{{out}}
Line 2,215: Line 2,215:


=={{header|Ol}}==
=={{header|Ol}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(define (dot-product a b)
(define (dot-product a b)
(apply + (map * a b)))
(apply + (map * a b)))
Line 2,221: Line 2,221:
(print (dot-product '(1 3 -5) '(4 -2 -1)))
(print (dot-product '(1 3 -5) '(4 -2 -1)))
; ==> 3
; ==> 3
</syntaxhighlight>
</lang>


=={{header|Oz}}==
=={{header|Oz}}==
Vectors are represented as lists in this example.
Vectors are represented as lists in this example.
<lang oz>declare
<syntaxhighlight lang="oz">declare
fun {DotProduct Xs Ys}
fun {DotProduct Xs Ys}
{Length Xs} = {Length Ys} %% assert
{Length Xs} = {Length Ys} %% assert
Line 2,231: Line 2,231:
end
end
in
in
{Show {DotProduct [1 3 ~5] [4 ~2 ~1]}}</lang>
{Show {DotProduct [1 3 ~5] [4 ~2 ~1]}}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>dot(u,v)={
<syntaxhighlight lang="parigp">dot(u,v)={
sum(i=1,#u,u[i]*v[i])
sum(i=1,#u,u[i]*v[i])
};</lang>
};</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 2,242: Line 2,242:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>sub dotprod
<syntaxhighlight lang="perl">sub dotprod
{
{
my($vec_a, $vec_b) = @_;
my($vec_a, $vec_b) = @_;
Line 2,254: Line 2,254:
my @vec_b = (4,-2,-1);
my @vec_b = (4,-2,-1);


print dotprod(\@vec_a,\@vec_b), "\n"; # 3</lang>
print dotprod(\@vec_a,\@vec_b), "\n"; # 3</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_mul</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">5</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}))</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_mul</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">5</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}))</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,266: Line 2,266:


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>def sq_mul
<syntaxhighlight lang="phixmonti">def sq_mul
0 tolist var c
0 tolist var c
len for
len for
Line 2,287: Line 2,287:
sq_mul
sq_mul
sq_sum
sq_sum
pstack</lang>
pstack</syntaxhighlight>


=={{header|PHP}}==
=={{header|PHP}}==
<lang php><?php
<syntaxhighlight lang="php"><?php
function dot_product($v1, $v2) {
function dot_product($v1, $v2) {
if (count($v1) != count($v2))
if (count($v1) != count($v2))
Line 2,298: Line 2,298:


echo dot_product(array(1, 3, -5), array(4, -2, -1)), "\n";
echo dot_product(array(1, 3, -5), array(4, -2, -1)), "\n";
?></lang>
?></syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
L1 = [1, 3, -5],
L1 = [1, 3, -5],
L2 = [4, -2, -1],
L2 = [4, -2, -1],
Line 2,311: Line 2,311:
dot_product(L1,L2) = _, L1.length != L2.length =>
dot_product(L1,L2) = _, L1.length != L2.length =>
throw($dot_product_not_same_length(L1,L2)).
throw($dot_product_not_same_length(L1,L2)).
dot_product(L1,L2) = sum([L1[I]*L2[I] : I in 1..L1.length]). </lang>
dot_product(L1,L2) = sum([L1[I]*L2[I] : I in 1..L1.length]). </syntaxhighlight>


{{out}}
{{out}}
Line 2,318: Line 2,318:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de dotProduct (A B)
<syntaxhighlight lang="picolisp">(de dotProduct (A B)
(sum * A B) )
(sum * A B) )


(dotProduct (1 3 -5) (4 -2 -1))</lang>
(dotProduct (1 3 -5) (4 -2 -1))</syntaxhighlight>
{{out}}<pre>-> 3</pre>
{{out}}<pre>-> 3</pre>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang PL/I>get (n);
<syntaxhighlight lang="pl/i">get (n);
begin;
begin;
declare (A(n), B(n)) float;
declare (A(n), B(n)) float;
Line 2,334: Line 2,334:
dot_product = sum(a*b);
dot_product = sum(a*b);
put (dot_product);
put (dot_product);
end;</lang>
end;</syntaxhighlight>


=={{header|Plain English}}==
=={{header|Plain English}}==
<lang plainenglish>To run:
<syntaxhighlight lang="plainenglish">To run:
Start up.
Start up.
Make an example vector and another example vector.
Make an example vector and another example vector.
Line 2,391: Line 2,391:
Add 4 to the other example vector.
Add 4 to the other example vector.
Add -2 to the other example vector.
Add -2 to the other example vector.
Add -1 to the other example vector.</lang>
Add -1 to the other example vector.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,398: Line 2,398:


=={{header|PostScript}}==
=={{header|PostScript}}==
<lang postscript>/dotproduct{
<syntaxhighlight lang="postscript">/dotproduct{
/x exch def
/x exch def
/y exch def
/y exch def
Line 2,414: Line 2,414:
-1 ==
-1 ==
}ifelse
}ifelse
}def</lang>
}def</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function dotproduct( $a, $b) {
function dotproduct( $a, $b) {
$a | foreach -Begin {$i = $res = 0} -Process { $res += $_*$b[$i++] } -End{$res}
$a | foreach -Begin {$i = $res = 0} -Process { $res += $_*$b[$i++] } -End{$res}
Line 2,423: Line 2,423:
dotproduct (1..2) (1..2)
dotproduct (1..2) (1..2)
dotproduct (1..10) (11..20)
dotproduct (1..10) (11..20)
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 2,432: Line 2,432:
=={{header|Prolog}}==
=={{header|Prolog}}==
Works with SWI-Prolog.
Works with SWI-Prolog.
<lang Prolog>dot_product(L1, L2, N) :-
<syntaxhighlight lang="prolog">dot_product(L1, L2, N) :-
maplist(mult, L1, L2, P),
maplist(mult, L1, L2, P),
sumlist(P, N).
sumlist(P, N).


mult(A,B,C) :-
mult(A,B,C) :-
C is A*B.</lang>
C is A*B.</syntaxhighlight>
Example :
Example :
<pre> ?- dot_product([1,3,-5], [4,-2,-1], N).
<pre> ?- dot_product([1,3,-5], [4,-2,-1], N).
Line 2,443: Line 2,443:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Procedure dotProduct(Array a(1),Array b(1))
<syntaxhighlight lang="purebasic">Procedure dotProduct(Array a(1),Array b(1))
Protected i, sum, length = ArraySize(a())
Protected i, sum, length = ArraySize(a())


Line 2,466: Line 2,466:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<lang python>def dotp(a,b):
<syntaxhighlight lang="python">def dotp(a,b):
assert len(a) == len(b), 'Vector sizes must match'
assert len(a) == len(b), 'Vector sizes must match'
return sum(aterm * bterm for aterm,bterm in zip(a, b))
return sum(aterm * bterm for aterm,bterm in zip(a, b))
Line 2,475: Line 2,475:
if __name__ == '__main__':
if __name__ == '__main__':
a, b = [1, 3, -5], [4, -2, -1]
a, b = [1, 3, -5], [4, -2, -1]
assert dotp(a,b) == 3</lang>
assert dotp(a,b) == 3</syntaxhighlight>




Line 2,484: Line 2,484:


{{Works with|Python|3.7}}
{{Works with|Python|3.7}}
<lang python>'''Dot product'''
<syntaxhighlight lang="python">'''Dot product'''


from operator import (mul)
from operator import (mul)
Line 2,574: Line 2,574:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Dot product of other vectors with [1, 3, -5]:
<pre>Dot product of other vectors with [1, 3, -5]:
Line 2,586: Line 2,586:
{{works with|QBasic|1.1}}
{{works with|QBasic|1.1}}
{{trans|FreeBASIC}}
{{trans|FreeBASIC}}
<lang qbasic>DIM zero3d(2) 'some example vectors
<syntaxhighlight lang="qbasic">DIM zero3d(2) 'some example vectors
zero3d(0) = 0!: zero3d(1) = 0!: zero3d(2) = 0!
zero3d(0) = 0!: zero3d(1) = 0!: zero3d(2) = 0!
DIM zero5d(4)
DIM zero5d(4)
Line 2,610: Line 2,610:
NEXT i
NEXT i
dot = dp
dot = dp
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery>[ 0 unrot witheach
<syntaxhighlight lang="quackery">[ 0 unrot witheach
[ over i^ peek *
[ over i^ peek *
rot + swap ]
rot + swap ]
drop ] is .prod ( [ [ --> n )
drop ] is .prod ( [ [ --> n )


' [ 1 3 -5 ] ' [ 4 -2 -1 ] .prod echo</lang>
' [ 1 3 -5 ] ' [ 4 -2 -1 ] .prod echo</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,627: Line 2,627:
=={{header|R}}==
=={{header|R}}==
Here are several ways to do the task.
Here are several ways to do the task.
<lang R>x <- c(1, 3, -5)
<syntaxhighlight lang="r">x <- c(1, 3, -5)
y <- c(4, -2, -1)
y <- c(4, -2, -1)


Line 2,642: Line 2,642:
}
}


dotp(x, y)</lang>
dotp(x, y)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket
(define (dot-product l r) (for/sum ([x l] [y r]) (* x y)))
(define (dot-product l r) (for/sum ([x l] [y r]) (* x y)))
Line 2,653: Line 2,653:
;; dot-product works on sequences such as vectors:
;; dot-product works on sequences such as vectors:
(dot-product #(1 2 3) #(4 5 6))
(dot-product #(1 2 3) #(4 5 6))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 2,659: Line 2,659:
{{works with|Rakudo|2010.07}}
{{works with|Rakudo|2010.07}}
We use the square-bracket meta-operator to turn the infix operator <code>+</code> into a reducing list operator, and the guillemet meta-operator to vectorize the infix operator <code>*</code>. Length validation is automatic in this form.
We use the square-bracket meta-operator to turn the infix operator <code>+</code> into a reducing list operator, and the guillemet meta-operator to vectorize the infix operator <code>*</code>. Length validation is automatic in this form.
<lang perl6>say [+] (1, 3, -5) »*« (4, -2, -1);</lang>
<syntaxhighlight lang="raku" line>say [+] (1, 3, -5) »*« (4, -2, -1);</syntaxhighlight>


=={{header|Rascal}}==
=={{header|Rascal}}==


<lang Rascal>import List;
<syntaxhighlight lang="rascal">import List;


public int dotProduct(list[int] L, list[int] M){
public int dotProduct(list[int] L, list[int] M){
Line 2,678: Line 2,678:
throw "vector sizes must match";
throw "vector sizes must match";
}
}
}</lang>
}</syntaxhighlight>


===Alternative solution===
===Alternative solution===
If a matrix is represented by a relation of <x-coordinate, y-coordinate, value>, then function below can be used to find the Dot product.
If a matrix is represented by a relation of <x-coordinate, y-coordinate, value>, then function below can be used to find the Dot product.
<lang Rascal>import Prelude;
<syntaxhighlight lang="rascal">import Prelude;


public real matrixDotproduct(rel[real x, real y, real v] column1, rel[real x, real y, real v] column2){
public real matrixDotproduct(rel[real x, real y, real v] column1, rel[real x, real y, real v] column2){
Line 2,693: Line 2,693:
<1.0,0.0,-51.0>, <1.0,1.0,167.0>, <1.0,2.0,24.0>,
<1.0,0.0,-51.0>, <1.0,1.0,167.0>, <1.0,2.0,24.0>,
<2.0,0.0,4.0>, <2.0,1.0,-68.0>, <2.0,2.0,-41.0>
<2.0,0.0,4.0>, <2.0,1.0,-68.0>, <2.0,2.0,-41.0>
};</lang>
};</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==


<lang REBOL>REBOL []
<syntaxhighlight lang="rebol">REBOL []


a: [1 3 -5]
a: [1 3 -5]
Line 2,712: Line 2,712:
]
]


dot-product a b</lang>
dot-product a b</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
===no error checking===
===no error checking===
<lang rexx>/*REXX program computes the dot product of two equal size vectors (of any size).*/
<syntaxhighlight lang="rexx">/*REXX program computes the dot product of two equal size vectors (of any size).*/
vectorA = ' 1 3 -5 ' /*populate vector A with some numbers*/
vectorA = ' 1 3 -5 ' /*populate vector A with some numbers*/
vectorB = ' 4 -2 -1 ' /* " " B " " " */
vectorB = ' 4 -2 -1 ' /* " " B " " " */
Line 2,731: Line 2,731:
$=$+word(A,j) * word(B,j) /* ··· and add the product to the sum.*/
$=$+word(A,j) * word(B,j) /* ··· and add the product to the sum.*/
end /*j*/
end /*j*/
return $ /*return the sum to function's invoker.*/</lang>
return $ /*return the sum to function's invoker.*/</syntaxhighlight>
'''output''' &nbsp; using the default (internal) inputs:
'''output''' &nbsp; using the default (internal) inputs:
<pre>
<pre>
Line 2,741: Line 2,741:


===with error checking===
===with error checking===
<lang rexx>/*REXX program computes the dot product of two equal size vectors (of any size).*/
<syntaxhighlight lang="rexx">/*REXX program computes the dot product of two equal size vectors (of any size).*/
vectorA = ' 1 3 -5 ' /*populate vector A with some numbers*/
vectorA = ' 1 3 -5 ' /*populate vector A with some numbers*/
vectorB = ' 4 -2 -1 ' /* " " B " " " */
vectorB = ' 4 -2 -1 ' /* " " B " " " */
Line 2,770: Line 2,770:
$=$ + #.1 * #.2 /* ··· and add the product to the sum.*/
$=$ + #.1 * #.2 /* ··· and add the product to the sum.*/
end /*j*/
end /*j*/
return $ /*return the sum to function's invoker.*/</lang>
return $ /*return the sum to function's invoker.*/</syntaxhighlight>
'''output''' &nbsp; is the same as the 1<sup>st</sup> REXX version. <br><br>
'''output''' &nbsp; is the same as the 1<sup>st</sup> REXX version. <br><br>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
aVector = [2, 3, 5]
aVector = [2, 3, 5]
bVector = [4, 2, 1]
bVector = [4, 2, 1]
Line 2,785: Line 2,785:
next
next
return sum
return sum
</syntaxhighlight>
</lang>


=={{header|RLaB}}==
=={{header|RLaB}}==
In its simplest form dot product is a composition of two functions: element-by-element
In its simplest form dot product is a composition of two functions: element-by-element
multiplication '.*' followed by sumation of an array. Consider an example:
multiplication '.*' followed by sumation of an array. Consider an example:
<lang RLaB>x = rand(1,10);
<syntaxhighlight lang="rlab">x = rand(1,10);
y = rand(1,10);
y = rand(1,10);
s = sum( x .* y );</lang>
s = sum( x .* y );</syntaxhighlight>
Warning: element-by-element multiplication is matrix optimized. As the interpretation of the matrix
Warning: element-by-element multiplication is matrix optimized. As the interpretation of the matrix
optimization is quite general, and unique to RLaB, any two matrices can be so multiplied irrespective
optimization is quite general, and unique to RLaB, any two matrices can be so multiplied irrespective
Line 2,800: Line 2,800:
=={{header|RPL}}==
=={{header|RPL}}==
Being a language for a calculator, RPL makes this easy.
Being a language for a calculator, RPL makes this easy.
<syntaxhighlight lang="rpl"><<
<lang RPL><<
[ 1 3 -5 ]
[ 1 3 -5 ]
[ 4 -2 -1 ]
[ 4 -2 -1 ]
DOT
DOT
>></lang>
>></syntaxhighlight>


=={{header|Ruby}}==
=={{header|Ruby}}==
With the '''standard library''', require 'matrix' and call Vector#inner_product.
With the '''standard library''', require 'matrix' and call Vector#inner_product.
<lang ruby>irb(main):001:0> require 'matrix'
<syntaxhighlight lang="ruby">irb(main):001:0> require 'matrix'
=> true
=> true
irb(main):002:0> Vector[1, 3, -5].inner_product Vector[4, -2, -1]
irb(main):002:0> Vector[1, 3, -5].inner_product Vector[4, -2, -1]
=> 3</lang>
=> 3</syntaxhighlight>
Or '''implement''' dot product.
Or '''implement''' dot product.
<lang ruby>class Array
<syntaxhighlight lang="ruby">class Array
def dot_product(other)
def dot_product(other)
raise "not the same size!" if self.length != other.length
raise "not the same size!" if self.length != other.length
Line 2,820: Line 2,820:
end
end


p [1, 3, -5].dot_product [4, -2, -1] # => 3</lang>
p [1, 3, -5].dot_product [4, -2, -1] # => 3</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>v1$ = "1, 3, -5"
<syntaxhighlight lang="runbasic">v1$ = "1, 3, -5"
v2$ = "4, -2, -1"
v2$ = "4, -2, -1"


Line 2,836: Line 2,836:
dotProduct = dotProduct + val(v1$) * val(v2$)
dotProduct = dotProduct + val(v1$) * val(v2$)
wend
wend
end function</lang>
end function</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
Implemented as a simple function with check for equal length of vectors.
Implemented as a simple function with check for equal length of vectors.
<lang rust>// alternatively, fn dot_product(a: &Vec<u32>, b: &Vec<u32>)
<syntaxhighlight lang="rust">// alternatively, fn dot_product(a: &Vec<u32>, b: &Vec<u32>)
// but using slices is more general and rustic
// but using slices is more general and rustic
fn dot_product(a: &[i32], b: &[i32]) -> Option<i32> {
fn dot_product(a: &[i32], b: &[i32]) -> Option<i32> {
Line 2,857: Line 2,857:


println!("{}", dot_product(&v1, &v2).unwrap());
println!("{}", dot_product(&v1, &v2).unwrap());
}</lang>
}</syntaxhighlight>




Line 2,863: Line 2,863:


'''Uses an unstable feature.'''
'''Uses an unstable feature.'''
<lang rust>#![feature(zero_one)] // <-- unstable feature
<syntaxhighlight lang="rust">#![feature(zero_one)] // <-- unstable feature
use std::ops::{Add, Mul};
use std::ops::{Add, Mul};
use std::num::Zero;
use std::num::Zero;
Line 2,891: Line 2,891:


println!("{}", dot_product(&v1, &v2).unwrap());
println!("{}", dot_product(&v1, &v2).unwrap());
}</lang>
}</syntaxhighlight>


=={{header|S-lang}}==
=={{header|S-lang}}==
<lang S-lang>print(sum([1, 3, -5] * [4, -2, -1]));</lang>
<syntaxhighlight lang="s-lang">print(sum([1, 3, -5] * [4, -2, -1]));</syntaxhighlight>
{{out}}
{{out}}
<pre>3.0</pre>
<pre>3.0</pre>
Line 2,902: Line 2,902:
=={{header|Sather}}==
=={{header|Sather}}==
Built-in class VEC "implements" euclidean (geometric) vectors.
Built-in class VEC "implements" euclidean (geometric) vectors.
<lang sather>class MAIN is
<syntaxhighlight lang="sather">class MAIN is
main is
main is
x ::= #VEC(|1.0, 3.0, -5.0|);
x ::= #VEC(|1.0, 3.0, -5.0|);
Line 2,908: Line 2,908:
#OUT + x.dot(y) + "\n";
#OUT + x.dot(y) + "\n";
end;
end;
end;</lang>
end;</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}<lang scala>class Dot[T](v1: Seq[T])(implicit n: Numeric[T]) {
{{libheader|Scala}}<syntaxhighlight lang="scala">class Dot[T](v1: Seq[T])(implicit n: Numeric[T]) {
import n._ // import * operator
import n._ // import * operator
def dot(v2: Seq[T]) = {
def dot(v2: Seq[T]) = {
Line 2,925: Line 2,925:
val v2 = List(4, -2, -1)
val v2 = List(4, -2, -1)
println(v1 dot v2)
println(v1 dot v2)
}</lang>
}</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^5</math>RS}}
{{Works with|Scheme|R<math>^5</math>RS}}
<lang scheme>(define (dot-product a b)
<syntaxhighlight lang="scheme">(define (dot-product a b)
(apply + (map * a b)))
(apply + (map * a b)))


(display (dot-product '(1 3 -5) '(4 -2 -1)))
(display (dot-product '(1 3 -5) '(4 -2 -1)))
(newline)</lang>
(newline)</syntaxhighlight>
{{out}}<pre>3</pre>
{{out}}<pre>3</pre>


=={{header|Scilab}}==
=={{header|Scilab}}==
<lang Scilab>A = [1 3 -5]
<syntaxhighlight lang="scilab">A = [1 3 -5]
B = [4 -2 -1]
B = [4 -2 -1]
C = sum(A.*B)</lang>
C = sum(A.*B)</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


$ syntax expr: .().dot.() is -> 6; # priority of dot operator
$ syntax expr: .().dot.() is -> 6; # priority of dot operator
Line 2,964: Line 2,964:
begin
begin
writeln([](1, 3, -5) dot [](4, -2, -1));
writeln([](1, 3, -5) dot [](4, -2, -1));
end func;</lang>
end func;</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func dot_product(a, b) {
<syntaxhighlight lang="ruby">func dot_product(a, b) {
(a »*« b)«+»;
(a »*« b)«+»;
};
};
say dot_product([1,3,-5], [4,-2,-1]); # => 3</lang>
say dot_product([1,3,-5], [4,-2,-1]); # => 3</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>v@(Vector traits) <dot> w@(Vector traits)
<syntaxhighlight lang="slate">v@(Vector traits) <dot> w@(Vector traits)
"Dot-product."
"Dot-product."
[
[
(0 below: (v size min: w size)) inject: 0 into:
(0 below: (v size min: w size)) inject: 0 into:
[| :sum :index | sum + ((v at: index) * (w at: index))]
[| :sum :index | sum + ((v at: index) * (w at: index))]
].</lang>
].</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
{{works with|GNU Smalltalk}}
<lang smalltalk>Array extend
<syntaxhighlight lang="smalltalk">Array extend
[
[
* anotherArray [
* anotherArray [
Line 2,993: Line 2,993:
]
]


( #(1 3 -5) * #(4 -2 -1 ) ) printNl.</lang>
( #(1 3 -5) * #(4 -2 -1 ) ) printNl.</syntaxhighlight>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
<lang snobol4> define("dotp(a,b)sum,i") :(dotp_end)
<syntaxhighlight lang="snobol4"> define("dotp(a,b)sum,i") :(dotp_end)
dotp i = 1; sum = 0
dotp i = 1; sum = 0
loop sum = sum + (a<i> * b<i>)
loop sum = sum + (a<i> * b<i>)
Line 3,006: Line 3,006:
b = array(3); b<1> = 4; b<2> = -2; b<3> = -1;
b = array(3); b<1> = 4; b<2> = -2; b<3> = -1;
output = dotp(a,b)
output = dotp(a,b)
end</lang>
end</syntaxhighlight>


=={{header|SPARK}}==
=={{header|SPARK}}==
Line 3,014: Line 3,014:


The precondition enforces equality of the ranges of the two vectors.
The precondition enforces equality of the ranges of the two vectors.
<lang ada>with Spark_IO;
<syntaxhighlight lang="ada">with Spark_IO;
--# inherit Spark_IO;
--# inherit Spark_IO;
--# main_program;
--# main_program;
Line 3,054: Line 3,054:
Width => 6,
Width => 6,
Base => 10);
Base => 10);
end Dot_Product_Main;</lang>
end Dot_Product_Main;</syntaxhighlight>
{{out}}<pre> 3</pre>
{{out}}<pre> 3</pre>


Line 3,063: Line 3,063:


Given two tables <code>A</code> and <code>B</code> where A has key columns <code>i</code> and <code>j</code> and B has key columns <code>j</code> and <code>k</code> and both have value columns <code>N</code>, the inner product of A and B would be:
Given two tables <code>A</code> and <code>B</code> where A has key columns <code>i</code> and <code>j</code> and B has key columns <code>j</code> and <code>k</code> and both have value columns <code>N</code>, the inner product of A and B would be:
<lang sql>select i, k, sum(A.N*B.N) as N
<syntaxhighlight lang="sql">select i, k, sum(A.N*B.N) as N
from A inner join B on A.j=B.j
from A inner join B on A.j=B.j
group by i, k</lang>
group by i, k</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
With lists:
With lists:
<lang sml>val dot = ListPair.foldlEq Real.*+ 0.0
<syntaxhighlight lang="sml">val dot = ListPair.foldlEq Real.*+ 0.0


(*
(*
- dot ([1.0, 3.0, ~5.0], [4.0, ~2.0, ~1.0]);
- dot ([1.0, 3.0, ~5.0], [4.0, ~2.0, ~1.0]);
val it = 3.0 : real
val it = 3.0 : real
*)</lang>
*)</syntaxhighlight>


With vectors:
With vectors:
<lang sml>fun dot (v, u) = (
<syntaxhighlight lang="sml">fun dot (v, u) = (
if Vector.length v <> Vector.length u then
if Vector.length v <> Vector.length u then
raise ListPair.UnequalLengths
raise ListPair.UnequalLengths
Line 3,087: Line 3,087:
- dot (#[1.0, 3.0, ~5.0], #[4.0, ~2.0, ~1.0]);
- dot (#[1.0, 3.0, ~5.0], #[4.0, ~2.0, ~1.0]);
val it = 3.0 : real
val it = 3.0 : real
*)</lang>
*)</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==
With row vectors:
With row vectors:


<lang stata>matrix a=1,3,-5
<syntaxhighlight lang="stata">matrix a=1,3,-5
matrix b=4,-2,-1
matrix b=4,-2,-1
matrix c=a*b'
matrix c=a*b'
di el("c",1,1)</lang>
di el("c",1,1)</syntaxhighlight>


With column vectors:
With column vectors:


<lang stata>matrix a=1\3\-5
<syntaxhighlight lang="stata">matrix a=1\3\-5
matrix b=4\-2\-1
matrix b=4\-2\-1
matrix c=a'*b
matrix c=a'*b
di el("c",1,1)</lang>
di el("c",1,1)</syntaxhighlight>


=== Mata ===
=== Mata ===
With row vectors:
With row vectors:


<lang stata>a=1,3,-5
<syntaxhighlight lang="stata">a=1,3,-5
b=4,-2,-1
b=4,-2,-1
a*b'</lang>
a*b'</syntaxhighlight>


With column vectors:
With column vectors:


<lang stata>a=1\3\-5
<syntaxhighlight lang="stata">a=1\3\-5
b=4\-2\-1
b=4\-2\-1
a'*b</lang>
a'*b</syntaxhighlight>


In both cases, one cas also write
In both cases, one cas also write


<lang stata>sum(a:*b)</lang>
<syntaxhighlight lang="stata">sum(a:*b)</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
{{works with|Swift|1.2+}}
{{works with|Swift|1.2+}}
<lang swift>func dot(v1: [Double], v2: [Double]) -> Double {
<syntaxhighlight lang="swift">func dot(v1: [Double], v2: [Double]) -> Double {
return reduce(lazy(zip(v1, v2)).map(*), 0, +)
return reduce(lazy(zip(v1, v2)).map(*), 0, +)
}
}


println(dot([1, 3, -5], [4, -2, -1]))</lang>
println(dot([1, 3, -5], [4, -2, -1]))</syntaxhighlight>
{{out}}
{{out}}
<pre>3.0</pre>
<pre>3.0</pre>
Line 3,133: Line 3,133:
=={{header|Tcl}}==
=={{header|Tcl}}==
{{tcllib|math::linearalgebra}}
{{tcllib|math::linearalgebra}}
<lang tcl>package require math::linearalgebra
<syntaxhighlight lang="tcl">package require math::linearalgebra


set a {1 3 -5}
set a {1 3 -5}
Line 3,139: Line 3,139:
set dotp [::math::linearalgebra::dotproduct $a $b]
set dotp [::math::linearalgebra::dotproduct $a $b]
proc pp vec {return \[[join $vec ,]\]}
proc pp vec {return \[[join $vec ,]\]}
puts "[pp $a] \u2219 [pp $b] = $dotp"</lang>
puts "[pp $a] \u2219 [pp $b] = $dotp"</syntaxhighlight>
{{out}}<pre>[1,3,-5] ∙ [4,-2,-1] = 3.0</pre>
{{out}}<pre>[1,3,-5] ∙ [4,-2,-1] = 3.0</pre>


=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
To perform a matrix dot product on TI-83, the trick is to use lists (and not to use matrices).
To perform a matrix dot product on TI-83, the trick is to use lists (and not to use matrices).
<lang ti83b>sum({1,3,–5}*{4,–2,–1})</lang>
<syntaxhighlight lang="ti83b">sum({1,3,–5}*{4,–2,–1})</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,160: Line 3,160:
=={{header|Ursala}}==
=={{header|Ursala}}==
A standard library function for dot products of floating point numbers exists, but a new one can be defined for integers as shown using the map operator (<code>*</code>) with the zip suffix (<code>p</code>) to construct a "zipwith" operator (<code>*p</code>), which operates on the integer <code>product</code> function. A catchable exception is thrown if the list lengths are unequal. This function is then composed (<code>+</code>) with a cumulative summation function, which is constructed from the binary <code>sum</code> function, and the reduction operator (<code>:-</code>) with <code>0</code> specified for the vacuous sum.
A standard library function for dot products of floating point numbers exists, but a new one can be defined for integers as shown using the map operator (<code>*</code>) with the zip suffix (<code>p</code>) to construct a "zipwith" operator (<code>*p</code>), which operates on the integer <code>product</code> function. A catchable exception is thrown if the list lengths are unequal. This function is then composed (<code>+</code>) with a cumulative summation function, which is constructed from the binary <code>sum</code> function, and the reduction operator (<code>:-</code>) with <code>0</code> specified for the vacuous sum.
<lang Ursala>#import int
<syntaxhighlight lang="ursala">#import int


dot = sum:-0+ product*p
dot = sum:-0+ product*p
Line 3,166: Line 3,166:
#cast %z
#cast %z


test = dot(<1,3,-5>,<4,-2,-1>)</lang>
test = dot(<1,3,-5>,<4,-2,-1>)</syntaxhighlight>
{{out}}<pre>3</pre>
{{out}}<pre>3</pre>


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Private Function dot_product(x As Variant, y As Variant) As Double
<syntaxhighlight lang="vb">Private Function dot_product(x As Variant, y As Variant) As Double
dot_product = WorksheetFunction.SumProduct(x, y)
dot_product = WorksheetFunction.SumProduct(x, y)
End Function
End Function
Line 3,176: Line 3,176:
Public Sub main()
Public Sub main()
Debug.Print dot_product([{1,3,-5}], [{4,-2,-1}])
Debug.Print dot_product([{1,3,-5}], [{4,-2,-1}])
End Sub</lang>{{out}}
End Sub</syntaxhighlight>{{out}}
<pre> 3</pre>
<pre> 3</pre>


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
WScript.Echo DotProduct("1,3,-5","4,-2,-1")
WScript.Echo DotProduct("1,3,-5","4,-2,-1")


Line 3,195: Line 3,195:
Next
Next
End Function
End Function
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 3,202: Line 3,202:
=={{header|Visual Basic}}==
=={{header|Visual Basic}}==
{{works with|Visual Basic|6}}
{{works with|Visual Basic|6}}
<lang vb>Option Explicit
<syntaxhighlight lang="vb">Option Explicit


Function DotProduct(a() As Long, b() As Long) As Long
Function DotProduct(a() As Long, b() As Long) As Long
Line 3,245: Line 3,245:
Debug.Assert Err.Description = "invalid input"
Debug.Assert Err.Description = "invalid input"
End Sub
End Sub
</syntaxhighlight>
</lang>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{trans|C#}}
{{trans|C#}}
<lang vbnet>Module Module1
<syntaxhighlight lang="vbnet">Module Module1


Function DotProduct(a As Decimal(), b As Decimal()) As Decimal
Function DotProduct(a As Decimal(), b As Decimal()) As Decimal
Line 3,260: Line 3,260:
End Sub
End Sub


End Module</lang>
End Module</syntaxhighlight>
{{out}}
{{out}}
<pre>3</pre>
<pre>3</pre>


=={{header|Vlang}}==
=={{header|Vlang}}==
<lang vlang>fn dot(x []int, y []int) ?int {
<syntaxhighlight lang="vlang">fn dot(x []int, y []int) ?int {
if x.len != y.len {
if x.len != y.len {
return error("incompatible lengths")
return error("incompatible lengths")
Line 3,280: Line 3,280:


println(d)
println(d)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,288: Line 3,288:


=={{header|Wart}}==
=={{header|Wart}}==
<lang python>def (dot_product x y)
<syntaxhighlight lang="python">def (dot_product x y)
(sum+map (*) x y)</lang>
(sum+map (*) x y)</syntaxhighlight>


<code>+</code> is punned (overloaded) here; when applied to functions it denotes composition. Also, <code>(*)</code> is used to skip infix expansion.
<code>+</code> is punned (overloaded) here; when applied to functions it denotes composition. Also, <code>(*)</code> is used to skip infix expansion.
Line 3,296: Line 3,296:


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>class Vector {
<syntaxhighlight lang="ecmascript">class Vector {
construct new(a) {
construct new(a) {
if (a.type != List || a.count == 0 || !a.all { |i| i is Num }) {
if (a.type != List || a.count == 0 || !a.all { |i| i is Num }) {
Line 3,322: Line 3,322:
var v2 = Vector.new([4, -2, -1])
var v2 = Vector.new([4, -2, -1])


System.print("The dot product of %(v1) and %(v2) is %(v1.dot(v2)).")</lang>
System.print("The dot product of %(v1) and %(v2) is %(v1.dot(v2)).")</syntaxhighlight>


{{out}}
{{out}}
Line 3,331: Line 3,331:
=={{header|X86 Assembly}}==
=={{header|X86 Assembly}}==
Using FASM. Targets x64 Microsoft Windows.
Using FASM. Targets x64 Microsoft Windows.
<lang asm>format PE64 console
<syntaxhighlight lang="asm">format PE64 console
entry start
entry start


Line 3,400: Line 3,400:


import msvcrt,\
import msvcrt,\
printf, 'printf'</lang>
printf, 'printf'</syntaxhighlight>
{{out}}<lang>3
{{out}}<syntaxhighlight lang="text">3
Size mismatch; can't calculate.
Size mismatch; can't calculate.
0</lang>
0</syntaxhighlight>


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes;
<syntaxhighlight lang="xpl0">include c:\cxpl\codes;


func DotProd(U, V, L);
func DotProd(U, V, L);
Line 3,418: Line 3,418:
[IntOut(0, DotProd([1, 3, -5], [4, -2, -1], 3));
[IntOut(0, DotProd([1, 3, -5], [4, -2, -1], 3));
CrLf(0);
CrLf(0);
]</lang>
]</syntaxhighlight>
{{out}}<pre>3</pre>
{{out}}<pre>3</pre>


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">
<lang Yabasic>
sub sq_mul(a(), b(), c())
sub sq_mul(a(), b(), c())
local n, i
local n, i
Line 3,451: Line 3,451:


print sq_sum(c())
print sq_sum(c())
</syntaxhighlight>
</lang>


=={{header|Zig}}==
=={{header|Zig}}==
<lang Zig>const std = @import("std");
<syntaxhighlight lang="zig">const std = @import("std");
const Vector = std.meta.Vector;
const Vector = std.meta.Vector;


Line 3,463: Line 3,463:


try std.io.getStdOut().writer().print("{d}\n", .{dot});
try std.io.getStdOut().writer().print("{d}\n", .{dot});
}</lang>
}</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn dotp(a,b){Utils.zipWith('*,a,b).sum()}</lang>
<syntaxhighlight lang="zkl">fcn dotp(a,b){Utils.zipWith('*,a,b).sum()}</syntaxhighlight>
zipWith stops at the shortest of the lists
zipWith stops at the shortest of the lists
{{out}}<pre>dotp(T(1,3,-5),T(4,-2,-1,666)) //-->3</pre>
{{out}}<pre>dotp(T(1,3,-5),T(4,-2,-1,666)) //-->3</pre>
If exact length is a requirement
If exact length is a requirement
<lang zkl>fcn dotp2(a,b){if(a.len()!=b.len())throw(Exception.ValueError);
<syntaxhighlight lang="zkl">fcn dotp2(a,b){if(a.len()!=b.len())throw(Exception.ValueError);
Utils.zipWith('*,a,b).sum()
Utils.zipWith('*,a,b).sum()
}</lang>
}</syntaxhighlight>


=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
<lang zxbasic>10 DIM a(3): LET a(1)=1: LET a(2)=3: LET a(3)=-5
<syntaxhighlight lang="zxbasic">10 DIM a(3): LET a(1)=1: LET a(2)=3: LET a(3)=-5
20 DIM b(3): LET b(1)=4: LET b(2)=-2: LET b(3)=-1
20 DIM b(3): LET b(1)=4: LET b(2)=-2: LET b(3)=-1
30 LET sum=0
30 LET sum=0
40 FOR i=1 TO 3: LET sum=sum+a(i)*b(i): NEXT i
40 FOR i=1 TO 3: LET sum=sum+a(i)*b(i): NEXT i
50 PRINT sum</lang>
50 PRINT sum</syntaxhighlight>
[[Category:Geometry]]
[[Category:Geometry]]