Dot product: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(Add CLU)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(39 intermediate revisions by 25 users not shown)
Line 23:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">print(dot((1, 3, -5), (4, -2, -1)))</langsyntaxhighlight>
{{out}}<pre>3</pre>
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Dot product 03/05/2016
DOTPROD CSECT
USING DOTPROD,R15
Line 50:
PG DC CL80' ' buffer
YREGS
END DOTPROD</langsyntaxhighlight>
{{out}}
<pre>
Line 57:
 
=={{header|8th}}==
<langsyntaxhighlight Forthlang="forth">[1,3,-5] [4,-2,-1] ' n:* ' n:+ a:dot . cr</langsyntaxhighlight>
{{out}}<pre>3</pre>
 
=={{header|ABAP}}==
<langsyntaxhighlight ABAPlang="abap">report zdot_product
data: lv_n type i,
lv_sum type i,
Line 86:
lv_sum = lv_sum + ( <wa_a> * <wa_b> ).
enddo.
endform.</langsyntaxhighlight>
{{out}}<pre>3</pre>
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun dotp (v u)
(if (or (endp v) (endp u))
0
(+ (* (first v) (first u))
(dotp (rest v) (rest u)))))</langsyntaxhighlight>
 
<pre>&gt; (dotp '(1 3 -5) '(4 -2 -1))
Line 100:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">INT FUNC DotProduct(INT ARRAY v1,v2 BYTE len)
BYTE i,res
 
Line 141:
 
Test(v1,v2,3)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Dot_product.png Screenshot from Atari 8-bit computer]
Line 149:
 
=={{header|ActionScript}}==
<langsyntaxhighlight ActionScriptlang="actionscript">function dotProduct(v1:Vector.<Number>, v2:Vector.<Number>):Number
{
if(v1.length != v2.length) return NaN;
Line 157:
return sum;
}
trace(dotProduct(Vector.<Number>([1,3,-5]),Vector.<Number>([4,-2,-1])));</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
procedure dot_product is
type vect is array(Positive range <>) of Integer;
Line 178:
begin
put_line(Integer'Image(dotprod(v1,v2)));
end dot_product;</langsyntaxhighlight>
{{out}}<pre>3</pre>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">real
dp(list a, list b)
{
Line 202:
 
0;
}</langsyntaxhighlight>
{{out}}<pre>3</pre>
 
Line 210:
{{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}}
<langsyntaxhighlight lang="algol68">MODE DOTFIELD = REAL;
MODE DOTVEC = [1:0]DOTFIELD;
 
Line 247:
 
print(("a SSDOT b = ",fixed(a SSDOT b,0,real width), new line));
print(("a * b = ",fixed(a * b,0,real width), new line))</langsyntaxhighlight>
{{out}}<pre>a SSDOT b = 3.000000000000000
a * b = 3.000000000000000</pre>
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% computes the dot product of two equal length integer vectors %
% (single dimension arrays ) the length of the vectors must be specified %
Line 275:
write( integerDotProduct( v1, v2, 3 ) )
end.
</syntaxhighlight>
</lang>
 
=={{header|Amazing Hopper}}==
Version 1:
<syntaxhighlight lang="c">
#include <basico.h>
 
principal {
imprimir(producto punto( lst'1,3,(-5)', lst'4,(-2),(-1)' ),NL)
terminar
}
</syntaxhighlight>
{{out}}
<pre>
3.00000
</pre>
Version 2:
<syntaxhighlight lang="c">
#define maincode main: {1}do
#define this {1}do
#defn out {"\n"}print
#define dotp mul;stats(0)
#defn lst(*) {"\033"} *;mklist;
#define ready {0}return
#define decim _X_DECIM=0, mov(_X_DECIM),prec(_X_DECIM),{1}do
 
main code{
{0}decim{
"A.B = "
this{
lst (1,3,(-5)), lst (4,(-2),(-1))
} dotp
} out
} ready
</syntaxhighlight>
{{out}}
<pre>
A.B = 3
</pre>
Version 3:
<syntaxhighlight lang="c">
#defn dotp(_X_,_Y_) #ATOM#CMPLX;#ATOM#CMPLX; mul; stats(0)
#defn lst(*) {"\033"} *;mklist;
#defn out(*) *;{"\n"}print
#defn code(*) main:; *; {"0"};return
 
code( out( dotp( lst (1,3,(-5)), lst (4,(-2),(-1)) ) ) )
</syntaxhighlight>
{{out}}
<pre>
3.00000
</pre>
<p>etc...</p>
 
=={{header|APL}}==
<langsyntaxhighlight APLlang="apl">1 3 ¯5 +.× 4 ¯2 ¯1</langsyntaxhighlight>
<b>Output:</b>
<pre>3</pre>
Line 284 ⟶ 336:
=={{header|AppleScript}}==
{{trans|JavaScript}} ( functional version )
<langsyntaxhighlight AppleScriptlang="applescript">----------------------- DOT PRODUCT -----------------------
 
-- dotProduct :: [Number] -> [Number] -> Number
Line 371 ⟶ 423:
return lst
end tell
end zipWith</langsyntaxhighlight>
{{Out}}
<syntaxhighlight lang="applescript">3</syntaxhighlight>
<lang AppleScript>3</lang>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">dotProduct: function [a,b][
[ensure equal? size a size b]
 
Line 388 ⟶ 440:
 
print dotProduct @[1, 3, neg 5] @[4, neg 2, neg 1]
print dotProduct [1 2 3] [4 5 6]</langsyntaxhighlight>
 
{{out}}
Line 396 ⟶ 448:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Vet1 := "1,3,-5"
Vet2 := "4 , -2 , -1"
MsgBox % DotProduct( Vet1 , Vet2 )
Line 412 ⟶ 464:
Sum += ArrayA%A_Index% * ArrayB%A_Index%
Return Sum
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f DOT_PRODUCT.AWK
BEGIN {
Line 433 ⟶ 485:
return(sum)
}
</syntaxhighlight>
</lang>
{{out}}<pre>3</pre>
 
Line 439 ⟶ 491:
==={{header|Applesoft BASIC}}===
Calculates the dot product of two random vectors of length N.
<langsyntaxhighlight lang="basic">
100 :
110 REM DOT PRODUCT
Line 460 ⟶ 512:
440 PRINT "] . [";: FOR I = 1 TO N: PRINT " ";V2(I);: NEXT I
450 PRINT "] = ";DP
</syntaxhighlight>
</lang>
{{out}}
<pre>]RUN
Line 469 ⟶ 521:
==={{header|BBC BASIC}}===
BBC BASIC has a built-in dot-product operator:
<langsyntaxhighlight lang="bbcbasic"> DIM vec1(2), vec2(2), dot(0)
vec1() = 1, 3, -5
Line 475 ⟶ 527:
dot() = vec1() . vec2()
PRINT "Result is "; dot(0)</langsyntaxhighlight>
{{out}}<pre>Result is 3</pre>
 
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">dim zero3d = {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 y = {0.0, 1.0, 0.0}
dim z = {0.0, 0.0, 1.0}
dim q = {1.0, 1.0, 3.14159}
dim r = {-1.0, 2.618033989, 3.0}
 
print " q dot r = "; dot(q, r)
print " zero3d dot zero5d = "; dot(zero3d, zero5d)
print " zero3d dot x = "; dot(zero3d, x)
print " z dot z = "; dot(z, z)
print " y dot z = "; dot(y, z)
end
 
function dot(a, b)
if a[?] <> b[?] then return "NaN"
 
dp = 0.0
for i = 0 to a[?]-1
dp += a[i] * b[i]
next i
return dp
end function</syntaxhighlight>
 
=={{header|bc}}==
<langsyntaxhighlight lang="bc">/* Calculate the dot product of two vectors a and b (represented as
* arrays) of size n.
*/
Line 497 ⟶ 576:
b[1] = -2
b[2] = -1
d(a[], b[], 3)</langsyntaxhighlight>
 
{{Out}}
Line 503 ⟶ 582:
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
let dotproduct(A, B, len) = valof
Line 516 ⟶ 595:
let B = table 4, -2, -1
writef("%N*N", dotproduct(A, B, 3))
$)</langsyntaxhighlight>
{{out}}
<pre>3</pre>
 
=={{header|Befunge 93}}==
<langsyntaxhighlight lang="befunge">
v Space for variables
v Space for vector1
Line 542 ⟶ 621:
>00g1-10p>10g:01-` | "
> ^
</syntaxhighlight>
</lang>
{{out}}<pre>Length:
3
Line 556 ⟶ 635:
 
Multiply the two vectors, then sum the result.
<langsyntaxhighlight lang="bqn">•Show 1‿3‿¯5 +´∘× 4‿¯2‿¯1
 
# as a tacit function
DotP ← +´×
•Show 1‿3‿¯5 DotP 4‿¯2‿¯1</langsyntaxhighlight>
<langsyntaxhighlight lang="bqn">3
3</langsyntaxhighlight>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat"> ( dot
= a A z Z
. !arg:(%?a ?z.%?A ?Z)
Line 571 ⟶ 650:
| 0
)
& out$(dot$(1 3 -5.4 -2 -1));</langsyntaxhighlight>
{{out}}<pre>3</pre>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 602 ⟶ 681:
 
return sum;
}</langsyntaxhighlight>
{{out}}<pre>3</pre>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">static void Main(string[] args)
{
Console.WriteLine(DotProduct(new decimal[] { 1, 3, -5 }, new decimal[] { 4, -2, -1 }));
Line 630 ⟶ 709:
 
return tVal;
}</langsyntaxhighlight>
{{out}}<pre>3</pre>
 
===Alternative using Linq (C# 4)===
{{works with|C sharp|C#|4}}
<langsyntaxhighlight lang="csharp">public static decimal DotProduct(decimal[] a, decimal[] b) {
return a.Zip(b, (x, y) => x * y).Sum();
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <numeric>
 
Line 651 ⟶ 730:
 
return 0;
}</langsyntaxhighlight>
{{out}}<pre>3</pre>
 
===Alternative using std::valarray===
<langsyntaxhighlight lang="cpp">
#include <valarray>
#include <iostream>
Line 669 ⟶ 748:
return 0;
}</langsyntaxhighlight>
{{out}}<pre>3</pre>
 
=== Alternative using std::inner_product ===
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <vector>
Line 684 ⟶ 763:
std::cout << "dot.product of {1,3,-5} and {4,-2,-1}: " << dp << std::endl;
return 0;
}</langsyntaxhighlight>
{{out}}<pre>dot.product of {1,3,-5} and {4,-2,-1}: 3</pre>
 
Line 690 ⟶ 769:
{{works with|Clojure|1.1}}
Preconditions are new in 1.1. The actual code also works in older Clojure versions.
<langsyntaxhighlight lang="clojure">(defn dot-product [& matrix]
{:pre [(apply == (map count matrix))]}
(apply + (apply map * matrix)))
Line 710 ⟶ 789:
(println (dot-product2 [1 3 -5] [4 -2 -1]))
(println (dot-product3 [1 3 -5] [4 -2 -1]))
</syntaxhighlight>
</lang>
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">% Compute the dot product of two sequences
% 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
Line 742 ⟶ 821:
 
stream$putl(po, int$unparse(dot_product[int](a,b)))
end start_up</langsyntaxhighlight>
{{out}}
<pre>3</pre>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">dot_product = (ary1, ary2) ->
if ary1.length != ary2.length
throw "can't find dot product: arrays have different lengths"
Line 759 ⟶ 838:
console.log dot_product([ 1, 3, -5 ], [ 4, -2, -1, 0 ]) # exception
catch e
console.log e</langsyntaxhighlight>
{{out}}<pre>> coffee foo.coffee
3
Line 765 ⟶ 844:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun dot-product (a b)
(apply #'+ (mapcar #'* (coerce a 'list) (coerce b 'list))))</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="lisp">(defun dot-prod (a b)
(reduce #'+ (map 'simple-vector #'* a b)))</langsyntaxhighlight>
 
=={{header|Component Pascal}}==
{{Works with|BlackBox Component Builder}}
<langsyntaxhighlight lang="oberon2">
MODULE DotProduct;
IMPORT StdLog;
Line 802 ⟶ 881:
 
END DotProduct.
</syntaxhighlight>
</lang>
Execute: ^Q DotProduct.Test
{{out}}
Line 810 ⟶ 889:
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
sub dotproduct(a: [int32], b: [int32], len: intptr): (n: int32) is
Line 834 ⟶ 913:
 
printsgn(dotproduct(&A[0], &B[0], @sizeof A));
print_nl();</langsyntaxhighlight>
{{out}}
<pre>3</pre>
 
=={{header|Craft Basic}}==
<syntaxhighlight lang="basic">dim a[1, 3, -5]
dim b[4, -2, -1]
 
arraysize n, a
 
for i = 0 to n - 1
 
let s = s + a[i] * b[i]
 
next i
 
print s</syntaxhighlight>
{{out| Output}}<pre>3</pre>
 
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">class Vector
property x, y, z
Line 859 ⟶ 953:
end
 
p [8, 13, -5].dot_product [4, -7, -11] # => -4</langsyntaxhighlight>
 
{{out}}<pre>3
Line 865 ⟶ 959:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.numeric;
 
[1.0, 3.0, -5.0].dotProduct([4.0, -2.0, -1.0]).writeln;
}</langsyntaxhighlight>
{{out}}
<pre>3</pre>
Using an array operation:
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm;
 
Line 880 ⟶ 974:
double[3] c = a[] * b[];
c[].sum.writeln;
}</langsyntaxhighlight>
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">num dot(List<num> A, List<num> B){
if (A.length != B.length){
throw new Exception('Vectors must be of equal size');
Line 898 ⟶ 992:
var k = [4,-2,-1];
print(dot(l,k));
}</langsyntaxhighlight>
{{out}}
<pre>3</pre>
Line 904 ⟶ 998:
=={{header|Delphi}}==
{{works with|Lazarus}}
<langsyntaxhighlight lang="delphi">program Project1;
 
{$APPTYPE CONSOLE}
Line 930 ⟶ 1,024:
WriteLn(DotProduct(x,y));
ReadLn;
end.</langsyntaxhighlight>
{{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.
Line 936 ⟶ 1,030:
=={{header|DWScript}}==
For arbitrary length vectors, using a precondition to check vector length:
<langsyntaxhighlight lang="delphi">function DotProduct(a, b : array of Float) : Float;
require
a.Length = b.Length;
Line 947 ⟶ 1,041:
end;
 
PrintLn(DotProduct([1,3,-5], [4,-2,-1]));</langsyntaxhighlight>
Using built-in 4D Vector type:
<langsyntaxhighlight lang="delphi">var a := Vector(1, 3, -5, 0);
var b := Vector(4, -2, -1, 0);
 
PrintLn(a * b);</langsyntaxhighlight>
Ouput in both cases:<pre>3</pre>
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">dot a b:
if /= len a len b:
Raise value-error "dot product needs two vectors with the same length"
Line 964 ⟶ 1,058:
+ * pop-from a pop-from b
 
!. dot [ 1 3 -5 ] [ 4 -2 -1 ]</langsyntaxhighlight>
{{out}}<pre>3</pre>
 
=={{header|Draco}}==
<syntaxhighlight lang="draco">proc nonrec dot_product([*] int a, b) int:
int total;
word i;
total := 0;
for i from 0 upto dim(a,1)-1 do
total := total + a[i] * b[i]
od;
total
corp
 
proc nonrec main() void:
[3] int a = (1, 3, -5);
[3] int b = (4, -2, -1);
write(dot_product(a, b))
corp</syntaxhighlight>
{{out}}
<pre>3</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
func dotprod a[] b[] .
for i to len a[]
r += a[i] * b[i]
.
return r
.
print dotprod [ 1 3 -5 ] [ 4 -2 -1 ]
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="lisp">
(define a #(1 3 -5))
(define b #(4 -2 -1))
Line 979 ⟶ 1,103:
(lib 'math)
(dot-product a b) → 3
</syntaxhighlight>
</lang>
 
=={{header|Eiffel}}==
<langsyntaxhighlight Eiffellang="eiffel">class
APPLICATION
 
Line 1,015 ⟶ 1,139:
end
end
end</langsyntaxhighlight>
 
Ouput:<pre>3</pre>
Line 1,021 ⟶ 1,145:
=={{header|Ela}}==
{{Trans|Haskell}}
<langsyntaxhighlight lang="ela">open list
 
dotp a b | length a == length b = sum (zipWith (*) a b)
| else = fail "Vector sizes must match."
 
dotp [1,3,-5] [4,-2,-1]</langsyntaxhighlight>
{{out}}<pre>3</pre>
 
=={{header|Elena}}==
ELENA 5.0 :
<langsyntaxhighlight lang="elena">import extensions;
import system'routines;
Line 1,043 ⟶ 1,167:
{
console.printLine(new int[]{1, 3, -5}.dotProduct(new int[]{4, -2, -1}))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,051 ⟶ 1,175:
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Vector do
def dot_product(a,b) when length(a)==length(b), do: dot_product(a,b,0)
def dot_product(_,_) do
Line 1,061 ⟶ 1,185:
end
 
IO.puts Vector.dot_product([1,3,-5],[4,-2,-1])</langsyntaxhighlight>
 
{{out}}
Line 1,068 ⟶ 1,192:
</pre>
 
=={{header|Emacs LispElm}}==
{{trans|Elm}}
<lang Emacs Lisp>
<syntaxhighlight lang="elm">dotp: List number -> List number -> Maybe number
(defun dot-product (v1 v2)
dotp a b =
(setq res 0)
(dotimes (i (if List.length v1))a /= List.length b then
Nothing
(setq res (+ (* (elt v1 i) (elt v2 i) ) res) ))
res) else
Just (List.sum <| List.map2 (*) a b)
 
dotp [1,3,-5] [4,-2,-1])</syntaxhighlight>
(progn
 
(insert (format "%d\n" (dot-product [1 2 3] [1 2 3]) ))
{{out}}
(insert (format "%d\n" (dot-product '(1 2 3) '(1 2 3) ))))
</langpre>
3
<b>Output:</b>
<pre>
14
14
</pre>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(defun dot-product (v1 v2)
(let ((res 0))
(dotimes (i (length v1))
(setq res (+ (* (elt v1 i) (elt v2 i)) res)))
res))
 
(dot-product [1 2 3] [1 2 3]) ;=> 14
(dot-product '(1 2 3) '(1 2 3)) ;=> 14</syntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">dotProduct(A,B) when length(A) == length(B) -> dotProduct(A,B,0);
dotProduct(_,_) -> erlang:error('Vectors must have the same length.').
 
Line 1,093 ⟶ 1,225:
dotProduct([],[],P) -> P.
 
dotProduct([1,3,-5],[4,-2,-1]).</langsyntaxhighlight>
{{out}}<pre>3</pre>
 
=={{header|Euphoria}}==
<langsyntaxhighlight Euphorialang="euphoria">function dotprod(sequence a, sequence b)
atom sum
a *= b
Line 1,107 ⟶ 1,239:
end function
 
? dotprod({1,3,-5},{4,-2,-1})</langsyntaxhighlight>
{{out}}
<pre>3</pre>
<langsyntaxhighlight Euphorialang="euphoria">-- Here is an alternative method,
-- using the standard Euphoria Version 4+ Math Library
include std/math.e
sequence a = {1,3,-5}, b = {4,-2,-1} -- Make them any length you want
? sum(a * b)</langsyntaxhighlight>
{{out}}<pre>3</pre>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight 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"
Array.fold2 (fun acc i j -> acc + (i * j)) 0 a b</langsyntaxhighlight>
<pre>&gt; dot_product [| 1; 3; -5 |] [| 4; -2; -1 |] ;;
val it : int = 3</pre>
Line 1,126 ⟶ 1,258:
=={{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.
<langsyntaxhighlight lang="factor">USING: kernel math.vectors sequences ;
 
: dot-product ( u v -- w )
2dup [ length ] bi@ =
[ v. ] [ "Vector lengths must be equal" throw ] if ;</langsyntaxhighlight>
 
( scratchpad ) { 1 3 -5 } { 4 -2 -1 } dot-product .
Line 1,136 ⟶ 1,268:
 
=={{header|FALSE}}==
<langsyntaxhighlight lang="false">[[\1-$0=~][$d;2*1+\-ø\$d;2+\-ø@*@+]#]p:
3d: {Vectors' length}
1 3 5_ 4 2_ 1_ d;$1+ø@*p;!%. {Output: 3}</langsyntaxhighlight>
 
=={{header|Fantom}}==
Dot product of lists of Int:
<langsyntaxhighlight lang="fantom">class DotProduct
{
static Int dotProduct (Int[] a, Int[] b)
Line 1,161 ⟶ 1,293:
echo ("Dot product of $x and $y is ${dotProduct(x, y)}")
}
}</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: vector create cells allot ;
: th cells + ;
 
Line 1,180 ⟶ 1,312:
-1 -2 4 b /vector vector!
 
a b /vector dotproduct . 3 ok</langsyntaxhighlight>
 
=={{header|Fortran}}==
 
<langsyntaxhighlight lang="fortran">program test_dot_product
 
write (*, '(i0)') dot_product ([1, 3, -5], [4, -2, -1])
 
end program test_dot_product</langsyntaxhighlight>
{{out}}<pre>3</pre>
 
Line 1,194 ⟶ 1,326:
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">dotProduct[v1, v2] :=
{
if length[v1] != length[v2]
Line 1,203 ⟶ 1,335:
return sum[map[{|c1,c2| c1 * c2}, zip[v1, v2]]]
}</langsyntaxhighlight>
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">import lists.zipWith
 
def dot( a, b )
Line 1,212 ⟶ 1,344:
| otherwise = error( "Vector sizes must match" )
 
println( dot([1, 3, -5], [4, -2, -1]) )</langsyntaxhighlight>
{{out}}<pre>3</pre>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight 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
Line 1,240 ⟶ 1,372:
print " zero3d dot x = ", dot(zero3d(), x())
print " z dot z = ", dot(z(), z())
print " y dot z = ", dot(y(), z())</langsyntaxhighlight>
{{out}}
<pre>
Line 1,248 ⟶ 1,380:
z dot z = 1
y dot z = 0</pre>
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn DotProduct( a as CFArrayRef, b as CFArrayRef ) as double
NSInteger i
double dp = 0.0
if len(a) != len(b) then alert 1, NSAlertStyleWarning,, @"Vectors have unequal length.", @"Okay" : exit fn
for i = 0 to len(a)-1
dp += fn NumberDoubleValue( a[i] ) * fn NumberDoubleValue( b[i] )
next
end fn = dp
 
CFArrayRef a, b
NSUInteger i
 
a = @[@1, @3, @-5]
b = @[@4, @-2, @-1]
printf @"Dot product of [%@, %@, %@].[%@, %@, %@] = %.4f", a[0], a[1], a[2], b[0], b[1], b[2], fn DotProduct( a, b )
 
a = @[@1.0, @1.0, @3.14159]
b = @[@-1.0, @2.618033989, @3.0]
printf @"Dot product of [%@, %@, %@].[%@, %@, %@] = %.4f", a[0], a[1], a[2], b[0], b[1], b[2], fn DotProduct( a, b )
 
a = @[@8, @13, @-5]
b = @[@4, @-7, @-11]
printf @"Dot product of [%@, %@, %@].[%@, %@, %@] = %.4f", a[0], a[1], a[2], b[0], b[1], b[2], fn DotProduct( a, b )
 
a = @[@1, @2, @3]
b = @[@7, @8, @9]
printf @"Dot product of [%@, %@, %@].[%@, %@, %@] = %.4f", a[0], a[1], a[2], b[0], b[1], b[2], fn DotProduct( a, b )
 
CFMutableArrayRef x, y
x = fn MutableArrayWithCapacity(0)
y = fn MutableArrayWithCapacity(0)
for i = 0 to 9 : MutableArrayInsertObjectAtIndex( x, fn NumberWithInteger(i+ 1), i ) : next
for i = 0 to 9 : MutableArrayInsertObjectAtIndex( y, fn NumberWithInteger(i+11), i ) : next
printf @"Dot product of [1…10].[11…20] = %.4f", fn DotProduct( fn ArrayWithArray( x ), fn ArrayWithArray( y ) )
NSLog( @"%@", fn WindowPrintViewString( 1 ) )
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Dot product of [1, 3, -5].[4, -2, -1] = 3.0000
Dot product of [1, 1, 3.14159].[-1, 2.618033989, 3] = 11.0428
Dot product of [8, 13, -5].[4, -7, -11] = -4.0000
Dot product of [1, 2, 3].[7, 8, 9] = 50.0000
Dot product of [1…10].[11…20] = 935.0000
</pre>
 
 
 
 
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Dot_product}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution'''
 
Dot product is intrinsically supported in Fōrmulæ.
 
'''Test case'''
 
[[File:Fōrmulæ - Dot product 01.png]]
 
[[File:Fōrmulæ - Dot product 02.png]]
 
'''Special cases'''
 
[[File:Fōrmulæ - Dot product 03.png]]
 
[[File:Fōrmulæ - Dot product 04.png]]
 
[[File:Fōrmulæ - Dot product 05.png]]
 
[[File:Fōrmulæ - Dot product 06.png]]
 
'''Programmed.''' A program can be created to calculate the dot product of two vectors:
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
[[File:Fōrmulæ - Dot product 07.png]]
In '''[https://formulae.org/?example=Dot_product this]''' page you can see the program(s) related to this task and their results.
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Built-in
 
[1, 3, -5]*[4, -2, -1];
# 3</langsyntaxhighlight>
 
=={{header|GLSL}}==
The dot product is built-in:
<langsyntaxhighlight lang="glsl">
float dot_product = dot(vec3(1, 3, -5), vec3(4, -2, -1));
</syntaxhighlight>
</lang>
 
=={{header|Go}}==
===Implementation===
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,300 ⟶ 1,510:
}
fmt.Println(d)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,306 ⟶ 1,516:
</pre>
===Library gonum/floats===
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,321 ⟶ 1,531:
func main() {
fmt.Println(floats.Dot(v1, v2))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,329 ⟶ 1,539:
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def dotProduct = { x, y ->
assert x && y && x.size() == y.size()
[x, y].transpose().collect{ xx, yy -> xx * yy }.sum()
}</langsyntaxhighlight>
Test:
<langsyntaxhighlight lang="groovy">println dotProduct([1, 3, -5], [4, -2, -1])</langsyntaxhighlight>
{{out}}<pre>3</pre>
 
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">dotp :: Num a => [a] -> [a] -> a
dotp a b | length a == length b = sum (zipWith (*) a b)
| otherwise = error "Vector sizes must match"
main = print $ dotp [1, 3, -5] [4, -2, -1] -- prints 3</langsyntaxhighlight>
 
Or, using the Maybe monad to avoid exceptions and keep things composable:
<syntaxhighlight lang="haskell">dotProduct :: Num a => [a] -> [a] -> Maybe a
<lang haskell>dotp
dotProduct a b
:: Num a
=>| length [a] ->== [a]length ->b Maybe= Just $ dp a b
dotp a b
| length a == length b = Just $ sum (zipWith (*) a b)
| otherwise = Nothing
where
dp x y = sum $ zipWith (*) x y
 
main :: IO ()
main = mbPrint $ dotp [1, 3, -5] [4, -2, -1] -- prints 3
 
main :: IO ()
mbPrint
main = print n
:: Show a
where
=> Maybe a -> IO ()
Just n = dotProduct [1, 3, -5] [4, -2, -1]</syntaxhighlight>
mbPrint (Just x) = print x
mbPrint n = print n</lang>
 
=={{header|Hoon}}==
<langsyntaxhighlight lang="hoon">|= [a=(list @sd) b=(list @sd)]
=| sum=@sd
|-
?: |(?=(~ a) ?=(~ b)) sum
$(a t.a, b t.b, sum (sum:si sum (pro:si i.a i.b)))</langsyntaxhighlight>
 
=={{header|Hy}}==
<langsyntaxhighlight lang="clojure">(defn dotp [a b]
(assert (= (len a) (len b)))
(sum (genexpr (* aterm bterm)
[(, aterm bterm) (zip a b)])))
 
(assert (= 3 (dotp [1 3 -5] [4 -2 -1])))</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight Iconlang="icon">procedure main()
write("a dot b := ",dotproduct([1, 3, -5],[4, -2, -1]))
end
Line 1,387 ⟶ 1,594:
every (dp := 0) +:= a[i := 1 to *a] * b[i]
return dp
end</langsyntaxhighlight>
 
=={{header|IDL}}==
<syntaxhighlight lang="idl">
<lang IDL>
a = [1, 3, -5]
b = [4, -2, -1]
c = a#TRANSPOSE(b)
c = TOTAL(a*b,/PRESERVE_TYPE)
</syntaxhighlight>
</lang>
 
=={{header|Idris}}==
<langsyntaxhighlight lang="idris">module Main
 
import Data.Vect
Line 1,407 ⟶ 1,614:
main : IO ()
main = printLn $ dotProduct [1,2,3] [1,2,3]
</syntaxhighlight>
</lang>
 
=={{header|J}}==
<langsyntaxhighlight lang="j"> 1 3 _5 +/ . * 4 _2 _1
3
dotp=: +/ . * NB. Or defined as a verb (function)
1 3 _5 dotp 4 _2 _1
3</langsyntaxhighlight>
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> ).
 
Spelling issue: The conjunction <code> .</code> needs to be preceded by a space. This is because J's spelling rules say that if the character '.' is preceded by any other character, it is included in the same parser token that included that other character. In other words, <code>1.23e4</code>, <code>'...'</code> and <code>/.</code> are each examples of "parser tokens".
 
=={{header|Janet}}==
<syntaxhighlight lang="janet">
(defn dot-product
"Calculates the dot product of two vectors."
[vec-a vec-b]
(assert (= (length vec-a) (length vec-b)) "Vector sizes must match")
(sum (map * vec-a vec-b)))
 
(print (dot-product [1 3 -5] [4 -2 -1]))
</syntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class DotProduct {
public static void main(String[] args) {
Line 1,439 ⟶ 1,657:
return sum;
}
}</langsyntaxhighlight>
{{out}}<pre>3.0</pre>
 
=={{header|JavaScript}}==
===ES5===
<langsyntaxhighlight lang="javascript">function dot_product(ary1, ary2) {
if (ary1.length != ary2.length)
throw "can't find dot product: arrays have different lengths";
Line 1,454 ⟶ 1,672:
 
print(dot_product([1,3,-5],[4,-2,-1])); // ==> 3
print(dot_product([1,3,-5],[4,-2,-1,0])); // ==> exception</langsyntaxhighlight>
 
We could also use map and reduce in lieu of iteration,
 
<langsyntaxhighlight lang="javascript">function dotp(x,y) {
function dotp_sum(a,b) { return a + b; }
function dotp_times(a,i) { return x[i] * y[i]; }
Line 1,467 ⟶ 1,685:
 
dotp([1,3,-5],[4,-2,-1]); // ==> 3
dotp([1,3,-5],[4,-2,-1,0]); // ==> exception</langsyntaxhighlight>
 
===ES6===
Composing functional primitives into a '''dotProduct()''' which returns a '''undefinednull''' value (rather than an error) when the array lengths are unmatched.
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'"use strict'";
 
// ------------------- DOT PRODUCT -------------------
// dotProduct :: [Int] -> [Int] -> Int
const dotProduct = (xs, ys) => {
const sum = xs => xs ? xs.reduce((a, b) => a + b, 0) : undefined;
 
// dotProduct :: [Num] -> [Num] -> Either Null Num
return xs.length === ys.length ? (
const dotProduct = xs =>
sum(zipWith((a, b) => a * b, xs, ys))
)ys :=> undefined;xs.length === ys.length
? sum(zipWith(mul)(xs)(ys))
}
: null;
 
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = (f, xs, ys) => {
const ny = ys.length;
return (xs.length <= ny ? xs : xs.slice(0, ny))
.map((x, i) => f(x, ys[i]));
}
 
// ---------------------- TEST -----------------------
return dotProduct([1, 3, -5], [4, -2, -1]);
})();</lang>
 
// main :: IO ()
{{Out}}
const main = () =>
<lang JavaScript>3</lang>
dotProduct([1, 3, -5])([4, -2, -1]);
 
 
// --------------------- GENERIC ---------------------
 
// mul :: Num -> Num -> Num
const mul = x =>
y => x * y;
 
 
// sum :: [Num] -> Num
const sum = xs =>
// The numeric sum of all values in xs.
xs.reduce((a, x) => a + x, 0);
 
 
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = f =>
// A list constructed by zipping with a
// custom function, rather than with the
// default tuple constructor.
xs => ys => xs.map(
(x, i) => f(x)(ys[i])
).slice(
0, Math.min(xs.length, ys.length)
);
 
// MAIN ---
return main();
})();</syntaxhighlight>
 
=={{header|jq}}==
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):
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,
Line 1,508 ⟶ 1,748:
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:<langsyntaxhighlight lang="jq">def SIGMA( f ): reduce .[] as $o (0; . + ($o | f )) ;</langsyntaxhighlight>
Given the array of objects as input, the dot-product is then simply <code>SIGMA( .x * .y )</code>.
 
Example:<langsyntaxhighlight lang="jq">dot( [1, 3, -5]; [4, -2, -1]) # => 3
 
[ {"x": 1, "y": 4}, {"x": 3, "y": -2}, {"x": -5, "y": -1} ]
| SIGMA( .x * .y ) # => 3</langsyntaxhighlight>
 
=={{header|Jsish}}==
From Javascript ES5 imperative entry.
<langsyntaxhighlight lang="javascript">/* Dot product, in Jsish */
function dot_product(ary1, ary2) {
if (ary1.length != ary2.length) throw "can't find dot product: arrays have different lengths";
Line 1,535 ⟶ 1,775:
PASS!: err = can't find dot product: arrays have different lengths
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 1,548 ⟶ 1,788:
=={{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]]).
<langsyntaxhighlight lang="julia">x = [1, 3, -5]
y = [4, -2, -1]
z = dot(x, y)
z = x'*y
z = x ⋅ y</langsyntaxhighlight>
 
=={{header|K}}==
<langsyntaxhighlight Klang="k"> +/1 3 -5 * 4 -2 -1
3
 
1 3 -5 _dot 4 -2 -1
3</langsyntaxhighlight>
 
=={{header|Klingphix}}==
<syntaxhighlight lang="text">:sq_mul
%c %i
( ) !c
Line 1,585 ⟶ 1,825:
pstack
 
" " input</langsyntaxhighlight>
 
=={{header|Kotlin}}==
{{works with|Kotlin|1.0+}}
<langsyntaxhighlight lang="scala">fun dot(v1: Array<Double>, v2: Array<Double>) =
v1.zip(v2).map { it.first * it.second }.reduce { a, b -> a + b }
 
fun main(args: Array<String>) {
dot(arrayOf(1.0, 3.0, -5.0), arrayOf(4.0, -2.0, -1.0)).let { println(it) }
}</langsyntaxhighlight>
{{out}}
<pre>3.0</pre>
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
{def dotp
{def dotp.r
Line 1,618 ⟶ 1,858:
{dotp {A.new 1 3 -5} {A.new 4 -2 -1}}
-> 3
</syntaxhighlight>
</lang>
 
=={{header|LFE}}==
<langsyntaxhighlight lang="lisp">(defun dot-product (a b)
(: lists foldl #'+/2 0
(: lists zipwith #'*/2 a b)))
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">vectorA$ = "1, 3, -5"
vectorB$ = "4, -2, -1"
print "DotProduct of ";vectorA$;" and "; vectorB$;" is ";
Line 1,650 ⟶ 1,890:
i = i+1
wend
end function </langsyntaxhighlight>
 
=={{header|LLVM}}==
<langsyntaxhighlight 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
; to just load the string into memory, and that would be boring.
Line 1,737 ⟶ 1,977:
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" }</langsyntaxhighlight>
{{out}}
<pre>3</pre>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to dotprod :a :b
output apply "sum (map "product :a :b)
end
 
show dotprod [1 3 -5] [4 -2 -1] ; 3</langsyntaxhighlight>
 
=={{header|Logtalk}}==
<langsyntaxhighlight lang="logtalk">dot_product(A, B, Sum) :-
dot_product(A, B, 0, Sum).
 
Line 1,755 ⟶ 1,995:
dot_product([A| As], [B| Bs], Acc, Sum) :-
Acc2 is Acc + A*B,
dot_product(As, Bs, Acc2, Sum).</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function dotprod(a, b)
local ret = 0
for i = 1, #a do
Line 1,766 ⟶ 2,006:
end
 
print(dotprod({1, 3, -5}, {4, -2, 1}))</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Version 12 can use types for arrays (earlier versions use variant type by default).
<lang M2000 Interpreter>
 
So we can adjust the return value of Dot() to be the same as the first item of first array. All functions of M2000 return variant type (including objects) or array of variant values, for multiple values (which is an object too).
 
<syntaxhighlight lang="m2000 interpreter">
Module dot_product {
A=(1,3,-5)
Line 1,776 ⟶ 2,020:
if len(a)<>len(b) Then Error "not same length"
if len(a)=0 then Error "empty vectors"
Letobject a1=each(a), b1=each(b), sum=0
// take type by first item in a()
long lowbound=dimension(a,1,0)
sum=a#val(lowbound)-a#val(lowbound)
While a1, b1 {sum+=array(a1)*array(b1)}
=sum
}
Print Dot(A, B)=3
Print Dot((1,3,-5), (4,-2,-1), 0)=3
dim k(2 to 4) as long long, z(3) as long long
k(2)=1,3,-5
z(0)=4,-2,-1
result=Dot(k(), z())
Print result=3, type$(result)="Long Long"
}
Module dot_product
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
Between Arrays, Vectors, or Matrices you can use the dot operator:
<langsyntaxhighlight Maplelang="maple"><1,2,3> . <4,5,6></langsyntaxhighlight>
<langsyntaxhighlight Maplelang="maple">Array([1,2,3]) . Array([4,5,6])</langsyntaxhighlight>
 
Between any of the above or lists, you can use the <code>LinearAlgebra[DotProduct]</code> function:
<langsyntaxhighlight Maplelang="maple">LinearAlgebra( <1,2,3>, <4,5,6> )</langsyntaxhighlight>
<langsyntaxhighlight Maplelang="maple">LinearAlgebra( Array([1,2,3]), Array([4,5,6]) )</langsyntaxhighlight>
<langsyntaxhighlight Maplelang="maple">LinearAlgebra([1,2,3], [4,5,6] )</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">{1,3,-5}.{4,-2,-1}</langsyntaxhighlight>
 
=={{header|MATLAB}}==
The dot product operation is a built-in function that operates on vectors of arbitrary length.
<langsyntaxhighlight lang="matlab">A = [1 3 -5]
B = [4 -2 -1]
C = dot(A,B)</langsyntaxhighlight>
For the Octave implimentation:
<langsyntaxhighlight lang="matlab">function C = DotPro(A,B)
C = sum( A.*B );
end</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">[1, 3, -5] . [4, -2, -1];
/* 3 */</langsyntaxhighlight>
 
=={{header|Mercury}}==
This will cause a software_error/1 exception if the lists are of different lengths.
<langsyntaxhighlight lang="mercury">:- module dot_product.
:- interface.
 
Line 1,831 ⟶ 2,083:
 
dot_product(As, Bs) =
list.foldl_corresponding((func(A, B, Acc) = Acc + A * B), As, Bs, 0).</langsyntaxhighlight>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">С/П * ИП0 + П0 С/П БП 00</langsyntaxhighlight>
 
''Input'': В/О x<sub>1</sub> С/П x<sub>2</sub> С/П y<sub>1</sub> С/П y<sub>2</sub> С/П ...
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE DotProduct;
FROM RealStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 1,863 ⟶ 2,115:
 
ReadChar
END DotProduct.</langsyntaxhighlight>
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">DOTPROD(A,B)
;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.
Line 1,874 ⟶ 2,126:
FOR I=1:1:$LENGTH(A,"^") SET SUM=SUM+($PIECE(A,"^",I)*$PIECE(B,"^",I))
KILL I
QUIT SUM</langsyntaxhighlight>
 
=={{header|Nemerle}}==
This will cause an exception if the arrays are different lengths.
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
using Nemerle.Collections.NCollectionsExtensions;
Line 1,894 ⟶ 2,146:
WriteLine(DotProduct(arr1, arr2));
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols binary
 
Line 1,917 ⟶ 2,169:
 
method dotProduct(vecs = double[,]) public constant returns double signals IllegalArgumentException
return dotProduct(vecs[0], vecs[1])</langsyntaxhighlight>
 
=={{header|newLISP}}==
<langsyntaxhighlight newLISPlang="newlisp">(define (dot-product x y)
(apply + (map * x y)))
 
(println (dot-product '(1 3 -5) '(4 -2 -1)))</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim"># Compile time error when a and b are differently sized arrays
# Runtime error when a and b are differently sized seqs
proc dotp[T](a,b: T): int =
Line 1,934 ⟶ 2,186:
 
echo dotp([1,3,-5], [4,-2,-1])
echo dotp(@[1,2,3],@[4,5,6])</langsyntaxhighlight>
 
Another version which allows to mix arrays and sequences provided they have the same length. It works also with miscellaneous number types (integers, floats).
 
<langsyntaxhighlight Nimlang="nim"># Runtime error if lengths of arrays or sequences differ.
 
func dotProduct[T](a, b: openArray[T]): T =
Line 1,947 ⟶ 2,199:
echo dotProduct([1,3,-5], [4,-2,-1])
echo dotProduct(@[1,2,3],@[4,5,6])
echo dotProduct([1.0, 2.0, 3.0], @[7.0, 8.0, 9.0])</langsyntaxhighlight>
 
=={{header|Oberon-2}}==
{{Works with|oo2c version 2}}
<langsyntaxhighlight lang="oberon2">
MODULE DotProduct;
IMPORT
Line 1,977 ⟶ 2,229:
Out.Int(DotProduct(x,y),0);Out.Ln
END DotProduct.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,984 ⟶ 2,236:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">bundle Default {
class DotProduct {
function : Main(args : String[]) ~ Nil {
Line 2,011 ⟶ 2,263:
}
}
}</langsyntaxhighlight>
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">#import <stdio.h>
#import <stdint.h>
#import <stdlib.h>
Line 2,120 ⟶ 2,372:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
With lists:
<langsyntaxhighlight 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];;
- : float = 3.
*)</langsyntaxhighlight>
 
With arrays:
<langsyntaxhighlight lang="ocaml">let dot v u =
if Array.length v <> Array.length u
then invalid_arg "Different array lengths";
Line 2,142 ⟶ 2,394:
# dot [| 1.0; 3.0; -5.0 |] [| 4.0; -2.0; -1.0 |];;
- : float = 3.
*)</langsyntaxhighlight>
 
=={{header|Octave}}==
See [[Dot product#MATLAB]] for an implementation. If we have a row-vector and a column-vector, we can use simply *.
<langsyntaxhighlight lang="octave">a = [1, 3, -5]
b = [4, -2, -1] % or [4; -2; -1] and avoid transposition with '
disp( a * b' ) % ' means transpose</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: dotProduct zipWith(#*) sum ;</langsyntaxhighlight>
 
{{out}}
Line 2,161 ⟶ 2,413:
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(define (dot-product a b)
(apply + (map * a b)))
Line 2,167 ⟶ 2,419:
(print (dot-product '(1 3 -5) '(4 -2 -1)))
; ==> 3
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
Vectors are represented as lists in this example.
<langsyntaxhighlight lang="oz">declare
fun {DotProduct Xs Ys}
{Length Xs} = {Length Ys} %% assert
Line 2,177 ⟶ 2,429:
end
in
{Show {DotProduct [1 3 ~5] [4 ~2 ~1]}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">dot(u,v)={
sum(i=1,#u,u[i]*v[i])
};</langsyntaxhighlight>
 
===Alternative===
<syntaxhighlight lang="parigp">dot(u,v) = u * v~;</syntaxhighlight>
 
=={{header|Pascal}}==
Line 2,188 ⟶ 2,443:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub dotprod
{
my($vec_a, $vec_b) = @_;
Line 2,200 ⟶ 2,455:
my @vec_b = (4,-2,-1);
 
print dotprod(\@vec_a,\@vec_b), "\n"; # 3</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,212 ⟶ 2,467:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">def sq_mul
0 tolist var c
len for
Line 2,233 ⟶ 2,488:
sq_mul
sq_sum
pstack</langsyntaxhighlight>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
function dot_product($v1, $v2) {
if (count($v1) != count($v2))
Line 2,244 ⟶ 2,499:
 
echo dot_product(array(1, 3, -5), array(4, -2, -1)), "\n";
?></langsyntaxhighlight>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
L1 = [1, 3, -5],
L2 = [4, -2, -1],
 
println(dot_product=dot_product(L1,L2)),
catch(println(dot_product([1,2,3,4],[1,2,3])),E, println(E)),
nl.
 
dot_product(L1,L2) = _, L1.length != L2.length =>
throw($dot_product_not_same_length(L1,L2)).
dot_product(L1,L2) = sum([L1[I]*L2[I] : I in 1..L1.length]). </syntaxhighlight>
 
{{out}}
<pre>dot_product = 3
dot_product_not_same_length([1,2,3,4],[1,2,3])</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de dotProduct (A B)
(sum * A B) )
 
(dotProduct (1 3 -5) (4 -2 -1))</langsyntaxhighlight>
{{out}}<pre>-> 3</pre>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">get (n);
begin;
declare (A(n), B(n)) float;
Line 2,263 ⟶ 2,535:
dot_product = sum(a*b);
put (dot_product);
end;</langsyntaxhighlight>
 
=={{header|Plain English}}==
<langsyntaxhighlight lang="plainenglish">To run:
Start up.
Make an example vector and another example vector.
Line 2,320 ⟶ 2,592:
Add 4 to the other example vector.
Add -2 to the other example vector.
Add -1 to the other example vector.</langsyntaxhighlight>
{{out}}
<pre>
Line 2,327 ⟶ 2,599:
 
=={{header|PostScript}}==
<langsyntaxhighlight lang="postscript">/dotproduct{
/x exch def
/y exch def
Line 2,343 ⟶ 2,615:
-1 ==
}ifelse
}def</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function dotproduct( $a, $b) {
$a | foreach -Begin {$i = $res = 0} -Process { $res += $_*$b[$i++] } -End{$res}
Line 2,352 ⟶ 2,624:
dotproduct (1..2) (1..2)
dotproduct (1..10) (11..20)
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,361 ⟶ 2,633:
=={{header|Prolog}}==
Works with SWI-Prolog.
<langsyntaxhighlight Prologlang="prolog">dot_product(L1, L2, N) :-
maplist(mult, L1, L2, P),
sumlist(P, N).
 
mult(A,B,C) :-
C is A*B.</langsyntaxhighlight>
Example :
<pre> ?- dot_product([1,3,-5], [4,-2,-1], N).
Line 2,372 ⟶ 2,644:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure dotProduct(Array a(1),Array b(1))
Protected i, sum, length = ArraySize(a())
 
Line 2,395 ⟶ 2,667:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">def dotp(a,b):
assert len(a) == len(b), 'Vector sizes must match'
return sum(aterm * bterm for aterm,bterm in zip(a, b))
Line 2,404 ⟶ 2,676:
if __name__ == '__main__':
a, b = [1, 3, -5], [4, -2, -1]
assert dotp(a,b) == 3</langsyntaxhighlight>
 
 
Line 2,413 ⟶ 2,685:
 
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Dot product'''
 
from operator import (mul)
Line 2,503 ⟶ 2,775:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Dot product of other vectors with [1, 3, -5]:
Line 2,511 ⟶ 2,783:
[4, 2, -1] -> 15
[4, -2, -1] -> 3</pre>
 
=={{header|QBasic}}==
{{works with|QBasic|1.1}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">DIM zero3d(2) 'some example vectors
zero3d(0) = 0!: zero3d(1) = 0!: zero3d(2) = 0!
DIM zero5d(4)
zero5d(0) = 0!: zero5d(1) = 0!: zero5d(2) = 0!: zero5d(3) = 0!: zero5d(4) = 0!
DIM x(2): x(0) = 1!: x(1) = 0!: x(2) = 0!
DIM y(2): y(0) = 0!: y(1) = 1!: y(2) = 0!
DIM z(2): z(0) = 0!: z(1) = 0!: z(2) = 1!
DIM q(2): q(0) = 1!: q(1) = 1!: q(2) = 3.14159
DIM r(2): r(0) = -1!: r(1) = 2.618033989#: r(2) = 3!
 
PRINT " q dot r = "; dot(q(), r())
PRINT " zero3d dot zero5d = "; dot(zero3d(), zero5d())
PRINT " zero3d dot x = "; dot(zero3d(), x())
PRINT " z dot z = "; dot(z(), z())
PRINT " y dot z = "; dot(y(), z())
 
FUNCTION dot (a(), b())
IF UBOUND(a) <> UBOUND(b) THEN dot = 0
dp = 0!
FOR i = 0 TO UBOUND(a)
dp = dp + (a(i) * b(i))
NEXT i
dot = dp
END FUNCTION</syntaxhighlight>
 
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery">[ 0 unrot witheach
[ over i^ peek *
rot + swap ]
drop ] is .prod ( [ [ --> n )
 
' [ 1 3 -5 ] ' [ 4 -2 -1 ] .prod echo</langsyntaxhighlight>
 
{{Out}}
Line 2,527 ⟶ 2,828:
=={{header|R}}==
Here are several ways to do the task.
<langsyntaxhighlight Rlang="r">x <- c(1, 3, -5)
y <- c(4, -2, -1)
 
Line 2,542 ⟶ 2,843:
}
 
dotp(x, y)</langsyntaxhighlight>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(define (dot-product l r) (for/sum ([x l] [y r]) (* x y)))
Line 2,553 ⟶ 2,854:
;; dot-product works on sequences such as vectors:
(dot-product #(1 2 3) #(4 5 6))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,559 ⟶ 2,860:
{{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.
<syntaxhighlight lang="raku" perl6line>saysub infix:<·> { [+] (1, 3, -5)@^a »*« (4,@^b -2, -1);</lang>}
 
say (1, 3, 5)·(4, -2, 1);</syntaxhighlight>
 
=={{header|Rascal}}==
 
<langsyntaxhighlight Rascallang="rascal">import List;
 
public int dotProduct(list[int] L, list[int] M){
Line 2,578 ⟶ 2,881:
throw "vector sizes must match";
}
}</langsyntaxhighlight>
 
===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.
<langsyntaxhighlight Rascallang="rascal">import Prelude;
 
public real matrixDotproduct(rel[real x, real y, real v] column1, rel[real x, real y, real v] column2){
Line 2,593 ⟶ 2,896:
<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>
};</langsyntaxhighlight>
 
=={{header|REBOL}}==
 
<langsyntaxhighlight REBOLlang="rebol">REBOL []
 
a: [1 3 -5]
Line 2,612 ⟶ 2,915:
]
 
dot-product a b</langsyntaxhighlight>
 
=={{header|REXX}}==
===noWith error checking===
<langsyntaxhighlight lang="rexx">/*REXX program computes the dot product of two equal size vectors (of any size).*/
vectorA = ' 1 3 -5 ' vectorA = ' 1 3 -5 ' /*populate vector A with some numbers*/
vectorB = ' 4 -2 -1 ' vectorB = ' 4 -2 -1 ' /* " " B " " " */
saySay 'vector A = ' vectorA /*display the elements in theof vector A. */
saySay 'vector B = ' vectorB /* " " " " " "B. B.*/
p=.Proddot_product(vectorA, vectorB) /*invoke function & compute dot product*/
say Say /*display a blank line for readability.*/
say Say 'dot product = ' p /*display the dot product to terminal. */
exit Exit /*stick a fork in it, we're all done. */
/*------------------------------------------------------------------------------*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
.Proddot_product: procedure; parse arg A,B /*this function compute the dot product */
Parse Arg A,B
$=0 /*initialize the sum to 0 (zero). */
/* Begin Error Checking do j=1 for words(A) /*multiply each number in the vectors. */
If words(A)<>words(B) Then
$=$+word(A,j) * word(B,j) /* ··· and add the product to the sum.*/
Call exit 'Vectors aren''t the same size:' words(A) '<>' words(B)
end /*j*/
Do i=1 To words(A)
return $ /*return the sum to function's invoker.*/</lang>
If datatype(word(A,i))<>'NUM' Then
Call exit 'Element' i 'of vector A isn''t a number:' word(A,i)
If datatype(word(B,i))<>'NUM' Then
Call exit 'Element' i 'of vector B isn''t a number:' word(B,i)
End
/* End Error Checking */
product=0 /* initialize the sum to 0 (zero).*/
Do i=1 To words(A)
product=product+word(A,i)*word(B,i) /*multiply corresponding numbers */
End
Return product
exit:
Say '***error***' arg(1)
Exit 13
</syntaxhighlight>
'''output''' &nbsp; using the default (internal) inputs:
<pre>
Line 2,637 ⟶ 2,955:
vector B = 4 -2 -1
 
dot product = 3</pre>
</pre>
 
===with error checking===
<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*/
vectorB = ' 4 -2 -1 ' /* " " B " " " */
say 'vector A = ' vectorA /*display the elements in the vector A.*/
say 'vector B = ' vectorB /* " " " " " " B.*/
p=.prod(vectorA, vectorB) /*invoke function & compute dot product*/
say /*display a blank line for readability.*/
say 'dot product = ' p /*display the dot product to terminal. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
.prod: procedure; parse arg A,B /*this function compute the dot product*/
lenA = words(A); @.1= 'A' /*the number of numbers in vector A. */
lenB = words(B); @.2= 'B' /* " " " " " " B. */
/*Also, define 2 literals to hold names*/
if lenA\==lenB then do; say "***error*** vectors aren't the same size:" /*oops*/
say ' vector A length = ' lenA
say ' vector B length = ' lenB
exit 13 /*exit pgm with bad─boy return code 13.*/
end
$=0 /*initialize the sum to 0 (zero). */
do j=1 for lenA /*multiply each number in the vectors. */
#.1=word(A,j) /*use array to hold 2 numbers at a time*/
#.2=word(B,j)
do k=1 for 2; if datatype(#.k,'N') then iterate
say "***error*** vector " @.k ' element' j,
" isn't numeric: " n.k; exit 13
end /*k*/
$=$ + #.1 * #.2 /* ··· and add the product to the sum.*/
end /*j*/
return $ /*return the sum to function's invoker.*/</lang>
'''output''' &nbsp; is the same as the 1<sup>st</sup> REXX version. <br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
aVector = [2, 3, 5]
bVector = [4, 2, 1]
Line 2,685 ⟶ 2,969:
next
return sum
</syntaxhighlight>
</lang>
 
=={{header|RLaB}}==
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:
<langsyntaxhighlight RLaBlang="rlab">x = rand(1,10);
y = rand(1,10);
s = sum( x .* y );</langsyntaxhighlight>
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
Line 2,700 ⟶ 2,984:
=={{header|RPL}}==
Being a language for a calculator, RPL makes this easy.
<lang RPL><<
[ 1 3 -5 ]
[ 4 -2 -1 ]
DOT
>></lang>
 
=={{header|Ruby}}==
With the '''standard library''', require 'matrix' and call Vector#inner_product.
<langsyntaxhighlight lang="ruby">irb(main):001:0> require 'matrix'
=> true
irb(main):002:0> Vector[1, 3, -5].inner_product Vector[4, -2, -1]
=> 3</langsyntaxhighlight>
Or '''implement''' dot product.
<langsyntaxhighlight lang="ruby">class Array
def dot_product(other)
raise "not the same size!" if self.length != other.length
self.zip(other).inject(0)sum {|dp, (a, b)| dp += a*b}
end
end
 
p [1, 3, -5].dot_product [4, -2, -1] # => 3</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">v1$ = "1, 3, -5"
v2$ = "4, -2, -1"
 
Line 2,736 ⟶ 3,018:
dotProduct = dotProduct + val(v1$) * val(v2$)
wend
end function</langsyntaxhighlight>
 
=={{header|Rust}}==
Implemented as a simple function with check for equal length of vectors.
<langsyntaxhighlight lang="rust">// alternatively, fn dot_product(a: &Vec<u32>, b: &Vec<u32>)
// but using slices is more general and rustic
fn dot_product(a: &[i32], b: &[i32]) -> Option<i32> {
Line 2,757 ⟶ 3,039:
 
println!("{}", dot_product(&v1, &v2).unwrap());
}</langsyntaxhighlight>
 
 
Line 2,763 ⟶ 3,045:
 
'''Uses an unstable feature.'''
<langsyntaxhighlight lang="rust">#![feature(zero_one)] // <-- unstable feature
use std::ops::{Add, Mul};
use std::num::Zero;
Line 2,791 ⟶ 3,073:
 
println!("{}", dot_product(&v1, &v2).unwrap());
}</langsyntaxhighlight>
 
=={{header|S-lang}}==
<langsyntaxhighlight Slang="s-lang">print(sum([1, 3, -5] * [4, -2, -1]));</langsyntaxhighlight>
{{out}}
<pre>3.0</pre>
Line 2,802 ⟶ 3,084:
=={{header|Sather}}==
Built-in class VEC "implements" euclidean (geometric) vectors.
<langsyntaxhighlight lang="sather">class MAIN is
main is
x ::= #VEC(|1.0, 3.0, -5.0|);
Line 2,808 ⟶ 3,090:
#OUT + x.dot(y) + "\n";
end;
end;</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}<langsyntaxhighlight lang="scala">class Dot[T](v1: Seq[T])(implicit n: Numeric[T]) {
import n._ // import * operator
def dot(v2: Seq[T]) = {
Line 2,825 ⟶ 3,107:
val v2 = List(4, -2, -1)
println(v1 dot v2)
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^5</math>RS}}
<langsyntaxhighlight lang="scheme">(define (dot-product a b)
(apply + (map * a b)))
 
(display (dot-product '(1 3 -5) '(4 -2 -1)))
(newline)</langsyntaxhighlight>
{{out}}<pre>3</pre>
 
=={{header|Scilab}}==
<langsyntaxhighlight Scilablang="scilab">A = [1 3 -5]
B = [4 -2 -1]
C = sum(A.*B)</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
$ syntax expr: .().dot.() is -> 6; # priority of dot operator
Line 2,864 ⟶ 3,146:
begin
writeln([](1, 3, -5) dot [](4, -2, -1));
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func dot_product(a, b) {
(a »*« b)«+»;
};
say dot_product([1,3,-5], [4,-2,-1]); # => 3</langsyntaxhighlight>
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">v@(Vector traits) <dot> w@(Vector traits)
"Dot-product."
[
(0 below: (v size min: w size)) inject: 0 into:
[| :sum :index | sum + ((v at: index) * (w at: index))]
].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<langsyntaxhighlight lang="smalltalk">Array extend
[
* anotherArray [
Line 2,893 ⟶ 3,175:
]
 
( #(1 3 -5) * #(4 -2 -1 ) ) printNl.</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
<langsyntaxhighlight lang="snobol4"> define("dotp(a,b)sum,i") :(dotp_end)
dotp i = 1; sum = 0
loop sum = sum + (a<i> * b<i>)
Line 2,906 ⟶ 3,188:
b = array(3); b<1> = 4; b<2> = -2; b<3> = -1;
output = dotp(a,b)
end</langsyntaxhighlight>
 
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "dotproduct" )
@( description, "Create a function/use an in-built function, to compute" )
@( description, "the dot product, also known as the scalar product of two" )
@( description, "vectors. If possible, make the vectors of arbitrary length." )
@( description, "As an example, compute the dot product of the vectors [1," )
@( description, " 3, -5] and [4, -2, -1]." )
@( description, "If implementing the dot product of two vectors directly," )
@( description, "each vector must be the same length; multiply" )
@( description, "corresponding terms from each vector then sum the results" )
@( description, "to produce the answer. " )
@( see_also, "http://rosettacode.org/wiki/Dot_product" )
@( author, "Ken O. Burtch" );
pragma license( unrestricted );
 
pragma restriction( no_external_commands );
 
procedure dotproduct is
type vect3 is array(1..3) of integer;
v1 : constant vect3 := (1,3,-5);
v2 : constant vect3 := (4,-2,-1);
 
sum_total : integer := 0;
begin
if arrays.length( v1 ) /= arrays.length( v2 ) then
put_line( standard_error, "different lengths" );
command_list.set_exit_status( 193 );
return;
end if;
if arrays.first( v1 ) /= arrays.first( v2 ) then
put_line( standard_error, "different starts" );
command_list.set_exit_status( 194 );
return;
end if;
for p in arrays.first( v1 )..arrays.last( v1 ) loop
sum_total := @ + v1(p)*v2(p);
end loop;
? sum_total;
end dotproduct;</syntaxhighlight>
 
=={{header|SPARK}}==
Line 2,914 ⟶ 3,238:
 
The precondition enforces equality of the ranges of the two vectors.
<langsyntaxhighlight lang="ada">with Spark_IO;
--# inherit Spark_IO;
--# main_program;
Line 2,954 ⟶ 3,278:
Width => 6,
Base => 10);
end Dot_Product_Main;</langsyntaxhighlight>
{{out}}<pre> 3</pre>
 
Line 2,963 ⟶ 3,287:
 
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:
<langsyntaxhighlight lang="sql">select i, k, sum(A.N*B.N) as N
from A inner join B on A.j=B.j
group by i, k</langsyntaxhighlight>
 
=={{header|Standard ML}}==
With lists:
<langsyntaxhighlight lang="sml">val dot = ListPair.foldlEq Real.*+ 0.0
 
(*
- dot ([1.0, 3.0, ~5.0], [4.0, ~2.0, ~1.0]);
val it = 3.0 : real
*)</langsyntaxhighlight>
 
With vectors:
<langsyntaxhighlight lang="sml">fun dot (v, u) = (
if Vector.length v <> Vector.length u then
raise ListPair.UnequalLengths
Line 2,987 ⟶ 3,311:
- dot (#[1.0, 3.0, ~5.0], #[4.0, ~2.0, ~1.0]);
val it = 3.0 : real
*)</langsyntaxhighlight>
 
=={{header|Stata}}==
With row vectors:
 
<langsyntaxhighlight lang="stata">matrix a=1,3,-5
matrix b=4,-2,-1
matrix c=a*b'
di el("c",1,1)</langsyntaxhighlight>
 
With column vectors:
 
<langsyntaxhighlight lang="stata">matrix a=1\3\-5
matrix b=4\-2\-1
matrix c=a'*b
di el("c",1,1)</langsyntaxhighlight>
 
=== Mata ===
With row vectors:
 
<langsyntaxhighlight lang="stata">a=1,3,-5
b=4,-2,-1
a*b'</langsyntaxhighlight>
 
With column vectors:
 
<langsyntaxhighlight lang="stata">a=1\3\-5
b=4\-2\-1
a'*b</langsyntaxhighlight>
 
In both cases, one cas also write
 
<syntaxhighlight lang ="stata">sum(a:*b)</langsyntaxhighlight>
 
=={{header|Swift}}==
{{works with|Swift|1.2+}}
<langsyntaxhighlight lang="swift">func dot(v1: [Double], v2: [Double]) -> Double {
return reduce(lazy(zip(v1, v2)).map(*), 0, +)
}
 
println(dot([1, 3, -5], [4, -2, -1]))</langsyntaxhighlight>
{{out}}
<pre>3.0</pre>
Line 3,033 ⟶ 3,357:
=={{header|Tcl}}==
{{tcllib|math::linearalgebra}}
<langsyntaxhighlight lang="tcl">package require math::linearalgebra
 
set a {1 3 -5}
Line 3,039 ⟶ 3,363:
set dotp [::math::linearalgebra::dotproduct $a $b]
proc pp vec {return \[[join $vec ,]\]}
puts "[pp $a] \u2219 [pp $b] = $dotp"</langsyntaxhighlight>
{{out}}<pre>[1,3,-5] ∙ [4,-2,-1] = 3.0</pre>
 
=={{header|TI-83 BASIC}}==
To perform a matrix dot product on TI-83, the trick is to use lists (and not to use matrices).
<langsyntaxhighlight lang="ti83b">sum({1,3,–5}*{4,–2,–1})</langsyntaxhighlight>
{{out}}
<pre>
Line 3,057 ⟶ 3,381:
3
</pre>
 
=={{header|True BASIC}}==
<syntaxhighlight lang="qbasic">FUNCTION dot (a(), b())
IF UBOUND(a) <> UBOUND(b) THEN LET dot = 0
LET dp = 0.0
FOR i = LBOUND(a) TO UBOUND(a)
LET dp = dp + (a(i) * b(i))
NEXT i
LET dot = dp
END FUNCTION
 
DIM zero3d(3)
LET zero3d(1) = 0.0
LET zero3d(2) = 0.0
LET zero3d(3) = 0.0
DIM zero5d(5)
LET zero5d(1) = 0.0
LET zero5d(2) = 0.0
LET zero5d(3) = 0.0
LET zero5d(4) = 0.0
LET zero5d(5) = 0.0
DIM x(3)
LET x(1) = 1.0
LET x(2) = 0.0
LET x(3) = 0.0
DIM y(3)
LET y(1) = 0.0
LET y(2) = 1.0
LET y(3) = 0.0
DIM z(3)
LET z(1) = 0.0
LET z(2) = 0.0
LET z(3) = 1.0
DIM q(3)
LET q(1) = 1.0
LET q(2) = 1.0
LET q(3) = 3.14159
DIM r(3)
LET r(1) = -1.0
LET r(2) = 2.618033989
LET r(3) = 3.0
 
PRINT " q dot r = "; dot(q(), r())
PRINT " zero3d dot zero5d = "; dot(zero3d(), zero5d())
PRINT " zero3d dot x = "; dot(zero3d(), x())
PRINT " z dot z = "; dot(z(), z())
PRINT " y dot z = "; dot(y(), z())
END</syntaxhighlight>
{{out}}
<pre>q dot r = 11.042804
zero3d dot zero5d = 0
zero3d dot x = 0
z dot z = 1
y dot z = 0</pre>
 
=={{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.
<langsyntaxhighlight Ursalalang="ursala">#import int
 
dot = sum:-0+ product*p
Line 3,066 ⟶ 3,444:
#cast %z
 
test = dot(<1,3,-5>,<4,-2,-1>)</langsyntaxhighlight>
{{out}}<pre>3</pre>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Private Function dot_product(x As Variant, y As Variant) As Double
dot_product = WorksheetFunction.SumProduct(x, y)
End Function
Line 3,076 ⟶ 3,454:
Public Sub main()
Debug.Print dot_product([{1,3,-5}], [{4,-2,-1}])
End Sub</langsyntaxhighlight>{{out}}
<pre> 3</pre>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
WScript.Echo DotProduct("1,3,-5","4,-2,-1")
 
Line 3,095 ⟶ 3,473:
Next
End Function
</syntaxhighlight>
</lang>
 
{{Out}}
Line 3,102 ⟶ 3,480:
=={{header|Visual Basic}}==
{{works with|Visual Basic|6}}
<langsyntaxhighlight lang="vb">Option Explicit
 
Function DotProduct(a() As Long, b() As Long) As Long
Line 3,145 ⟶ 3,523:
Debug.Assert Err.Description = "invalid input"
End Sub
</syntaxhighlight>
</lang>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Function DotProduct(a As Decimal(), b As Decimal()) As Decimal
Line 3,160 ⟶ 3,538:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>3</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
fn dot(x []int, y []int) !int {
if x.len != y.len {
return error("incompatible lengths")
}
mut r := 0
for i, xi in x {
r += xi * y[i]
}
return r
}
fn main() {
d := dot([1, 3, -5], [4, -2, -1])!
 
println(d)
}
</syntaxhighlight>
 
{{out}}
<pre>
3
</pre>
 
=={{header|Wart}}==
<langsyntaxhighlight lang="python">def (dot_product x y)
(sum+map (*) x y)</langsyntaxhighlight>
 
<code>+</code> is punned (overloaded) here; when applied to functions it denotes composition. Also, <code>(*)</code> is used to skip infix expansion.
Line 3,173 ⟶ 3,576:
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">class Vector {
construct new(a) {
if (a.type != List || a.count == 0 || !a.all { |i| i is Num }) {
Line 3,199 ⟶ 3,602:
var v2 = Vector.new([4, -2, -1])
 
System.print("The dot product of %(v1) and %(v2) is %(v1.dot(v2)).")</langsyntaxhighlight>
 
{{out}}
<pre>
The dot product of [1, 3, -5] and [4, -2, -1] is 3.
</pre>
 
{{libheader|Wren-vector}}
Alternatively, using the above module:
<syntaxhighlight lang="wren">import "./vector" for Vector3
 
var v1 = Vector3.new(1, 3, -5)
var v2 = Vector3.new(4, -2, -1)
 
System.print("The dot product of %(v1) and %(v2) is %(v1.dot(v2)).")</syntaxhighlight>
 
{{out}}
<pre>
The dot product of (1, 3, -5) and (4, -2, -1) is 3.
</pre>
 
=={{header|X86 Assembly}}==
Using FASM. Targets x64 Microsoft Windows.
<langsyntaxhighlight lang="asm">format PE64 console
entry start
 
Line 3,277 ⟶ 3,694:
 
import msvcrt,\
printf, 'printf'</langsyntaxhighlight>
{{out}}<syntaxhighlight lang="text">3
Size mismatch; can't calculate.
0</langsyntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
 
func DotProd(U, V, L);
Line 3,295 ⟶ 3,712:
[IntOut(0, DotProd([1, 3, -5], [4, -2, -1], 3));
CrLf(0);
]</langsyntaxhighlight>
{{out}}<pre>3</pre>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">
<lang Yabasic>
sub sq_mul(a(), b(), c())
local n, i
Line 3,328 ⟶ 3,745:
 
print sq_sum(c())
</syntaxhighlight>
</lang>
 
=={{header|Zig}}==
<syntaxhighlight lang="zig">const std = @import("std");
const Vector = std.meta.Vector;
 
pub fn main() !void {
const a: Vector(3, i32) = [_]i32{1, 3, -5};
const b: Vector(3, i32) = [_]i32{4, -2, -1};
var dot: i32 = @reduce(.Add, a*b);
 
try std.io.getStdOut().writer().print("{d}\n", .{dot});
}</syntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn dotp(a,b){Utils.zipWith('*,a,b).sum()}</langsyntaxhighlight>
zipWith stops at the shortest of the lists
{{out}}<pre>dotp(T(1,3,-5),T(4,-2,-1,666)) //-->3</pre>
If exact length is a requirement
<langsyntaxhighlight lang="zkl">fcn dotp2(a,b){if(a.len()!=b.len())throw(Exception.ValueError);
Utils.zipWith('*,a,b).sum()
}</langsyntaxhighlight>
 
=={{header|ZX Spectrum Basic}}==
<langsyntaxhighlight 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
30 LET sum=0
40 FOR i=1 TO 3: LET sum=sum+a(i)*b(i): NEXT i
50 PRINT sum</langsyntaxhighlight>
[[Category:Geometry]]
9,476

edits