Dot product: Difference between revisions
m
syntax highlighting fixup automation
(Dot product in BASIC256) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 23:
=={{header|11l}}==
<
{{out}}<pre>3</pre>
=={{header|360 Assembly}}==
<
DOTPROD CSECT
USING DOTPROD,R15
Line 50:
PG DC CL80' ' buffer
YREGS
END DOTPROD</
{{out}}
<pre>
Line 57:
=={{header|8th}}==
<
{{out}}<pre>3</pre>
=={{header|ABAP}}==
<
data: lv_n type i,
lv_sum type i,
Line 86:
lv_sum = lv_sum + ( <wa_a> * <wa_b> ).
enddo.
endform.</
{{out}}<pre>3</pre>
=={{header|ACL2}}==
<
(if (or (endp v) (endp u))
0
(+ (* (first v) (first u))
(dotp (rest v) (rest u)))))</
<pre>> (dotp '(1 3 -5) '(4 -2 -1))
Line 100:
=={{header|Action!}}==
<
BYTE i,res
Line 141:
Test(v1,v2,3)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Dot_product.png Screenshot from Atari 8-bit computer]
Line 149:
=={{header|ActionScript}}==
<
{
if(v1.length != v2.length) return NaN;
Line 157:
return sum;
}
trace(dotProduct(Vector.<Number>([1,3,-5]),Vector.<Number>([4,-2,-1])));</
=={{header|Ada}}==
<
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;</
{{out}}<pre>3</pre>
=={{header|Aime}}==
<
dp(list a, list b)
{
Line 202:
0;
}</
{{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}}
<
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))</
{{out}}<pre>a SSDOT b = 3.000000000000000
a * b = 3.000000000000000</pre>
=={{header|ALGOL W}}==
<
% 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>
=={{header|APL}}==
<
<b>Output:</b>
<pre>3</pre>
Line 284:
=={{header|AppleScript}}==
{{trans|JavaScript}} ( functional version )
<
-- dotProduct :: [Number] -> [Number] -> Number
Line 371:
return lst
end tell
end zipWith</
{{Out}}
<syntaxhighlight lang="applescript">3</syntaxhighlight>
=={{header|Arturo}}==
<
[ensure equal? size a size b]
Line 388:
print dotProduct @[1, 3, neg 5] @[4, neg 2, neg 1]
print dotProduct [1 2 3] [4 5 6]</
{{out}}
Line 396:
=={{header|AutoHotkey}}==
<
Vet2 := "4 , -2 , -1"
MsgBox % DotProduct( Vet1 , Vet2 )
Line 412:
Sum += ArrayA%A_Index% * ArrayB%A_Index%
Return Sum
}</
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f DOT_PRODUCT.AWK
BEGIN {
Line 433:
return(sum)
}
</syntaxhighlight>
{{out}}<pre>3</pre>
Line 439:
==={{header|Applesoft BASIC}}===
Calculates the dot product of two random vectors of length N.
<
100 :
110 REM DOT PRODUCT
Line 460:
440 PRINT "] . [";: FOR I = 1 TO N: PRINT " ";V2(I);: NEXT I
450 PRINT "] = ";DP
</syntaxhighlight>
{{out}}
<pre>]RUN
Line 469:
==={{header|BBC BASIC}}===
BBC BASIC has a built-in dot-product operator:
<
vec1() = 1, 3, -5
Line 475:
dot() = vec1() . vec2()
PRINT "Result is "; dot(0)</
{{out}}<pre>Result is 3</pre>
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<
dim zero5d = {0.0, 0.0, 0.0, 0.0, 0.0}
dim x = {1.0, 0.0, 0.0}
Line 503:
next i
return dp
end function</
=={{header|bc}}==
<
* arrays) of size n.
*/
Line 524:
b[1] = -2
b[2] = -1
d(a[], b[], 3)</
{{Out}}
Line 530:
=={{header|BCPL}}==
<
let dotproduct(A, B, len) = valof
Line 543:
let B = table 4, -2, -1
writef("%N*N", dotproduct(A, B, 3))
$)</
{{out}}
<pre>3</pre>
=={{header|Befunge 93}}==
<
v Space for variables
v Space for vector1
Line 569:
>00g1-10p>10g:01-` | "
> ^
</syntaxhighlight>
{{out}}<pre>Length:
3
Line 583:
Multiply the two vectors, then sum the result.
<
# as a tacit function
DotP ← +´×
•Show 1‿3‿¯5 DotP 4‿¯2‿¯1</
<
3</
=={{header|Bracmat}}==
<
= a A z Z
. !arg:(%?a ?z.%?A ?Z)
Line 598:
| 0
)
& out$(dot$(1 3 -5.4 -2 -1));</
{{out}}<pre>3</pre>
=={{header|C}}==
<
#include <stdlib.h>
Line 629:
return sum;
}</
{{out}}<pre>3</pre>
=={{header|C sharp|C#}}==
<
{
Console.WriteLine(DotProduct(new decimal[] { 1, 3, -5 }, new decimal[] { 4, -2, -1 }));
Line 657:
return tVal;
}</
{{out}}<pre>3</pre>
===Alternative using Linq (C# 4)===
{{works with|C sharp|C#|4}}
<
return a.Zip(b, (x, y) => x * y).Sum();
}</
=={{header|C++}}==
<
#include <numeric>
Line 678:
return 0;
}</
{{out}}<pre>3</pre>
===Alternative using std::valarray===
<
#include <valarray>
#include <iostream>
Line 696:
return 0;
}</
{{out}}<pre>3</pre>
=== Alternative using std::inner_product ===
<
#include <iostream>
#include <vector>
Line 711:
std::cout << "dot.product of {1,3,-5} and {4,-2,-1}: " << dp << std::endl;
return 0;
}</
{{out}}<pre>dot.product of {1,3,-5} and {4,-2,-1}: 3</pre>
Line 717:
{{works with|Clojure|1.1}}
Preconditions are new in 1.1. The actual code also works in older Clojure versions.
<
{:pre [(apply == (map count matrix))]}
(apply + (apply map * matrix)))
Line 737:
(println (dot-product2 [1 3 -5] [4 -2 -1]))
(println (dot-product3 [1 3 -5] [4 -2 -1]))
</syntaxhighlight>
=={{header|CLU}}==
<
% 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 769:
stream$putl(po, int$unparse(dot_product[int](a,b)))
end start_up</
{{out}}
<pre>3</pre>
=={{header|CoffeeScript}}==
<
if ary1.length != ary2.length
throw "can't find dot product: arrays have different lengths"
Line 786:
console.log dot_product([ 1, 3, -5 ], [ 4, -2, -1, 0 ]) # exception
catch e
console.log e</
{{out}}<pre>> coffee foo.coffee
3
Line 792:
=={{header|Common Lisp}}==
<
(apply #'+ (mapcar #'* (coerce a 'list) (coerce b 'list))))</
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.
<
(reduce #'+ (map 'simple-vector #'* a b)))</
=={{header|Component Pascal}}==
{{Works with|BlackBox Component Builder}}
<
MODULE DotProduct;
IMPORT StdLog;
Line 829:
END DotProduct.
</syntaxhighlight>
Execute: ^Q DotProduct.Test
{{out}}
Line 837:
=={{header|Cowgol}}==
<
sub dotproduct(a: [int32], b: [int32], len: intptr): (n: int32) is
Line 861:
printsgn(dotproduct(&A[0], &B[0], @sizeof A));
print_nl();</
{{out}}
<pre>3</pre>
Line 867:
=={{header|Crystal}}==
{{trans|Ruby}}
<
property x, y, z
Line 886:
end
p [8, 13, -5].dot_product [4, -7, -11] # => -4</
{{out}}<pre>3
Line 892:
=={{header|D}}==
<
import std.stdio, std.numeric;
[1.0, 3.0, -5.0].dotProduct([4.0, -2.0, -1.0]).writeln;
}</
{{out}}
<pre>3</pre>
Using an array operation:
<
import std.stdio, std.algorithm;
Line 907:
double[3] c = a[] * b[];
c[].sum.writeln;
}</
=={{header|Dart}}==
<
if (A.length != B.length){
throw new Exception('Vectors must be of equal size');
Line 925:
var k = [4,-2,-1];
print(dot(l,k));
}</
{{out}}
<pre>3</pre>
Line 931:
=={{header|Delphi}}==
{{works with|Lazarus}}
<
{$APPTYPE CONSOLE}
Line 957:
WriteLn(DotProduct(x,y));
ReadLn;
end.</
{{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 963:
=={{header|DWScript}}==
For arbitrary length vectors, using a precondition to check vector length:
<
require
a.Length = b.Length;
Line 974:
end;
PrintLn(DotProduct([1,3,-5], [4,-2,-1]));</
Using built-in 4D Vector type:
<
var b := Vector(4, -2, -1, 0);
PrintLn(a * b);</
Ouput in both cases:<pre>3</pre>
=={{header|Déjà Vu}}==
<
if /= len a len b:
Raise value-error "dot product needs two vectors with the same length"
Line 991:
+ * pop-from a pop-from b
!. dot [ 1 3 -5 ] [ 4 -2 -1 ]</
{{out}}<pre>3</pre>
=={{header|Draco}}==
<
int total;
word i;
Line 1,009:
[3] int b = (4, -2, -1);
write(dot_product(a, b))
corp</
{{out}}
<pre>3</pre>
=={{header|EchoLisp}}==
<
(define a #(1 3 -5))
(define b #(4 -2 -1))
Line 1,025:
(lib 'math)
(dot-product a b) → 3
</syntaxhighlight>
=={{header|Eiffel}}==
<
APPLICATION
Line 1,061:
end
end
end</
Ouput:<pre>3</pre>
Line 1,067:
=={{header|Ela}}==
{{Trans|Haskell}}
<
dotp a b | length a == length b = sum (zipWith (*) a b)
| else = fail "Vector sizes must match."
dotp [1,3,-5] [4,-2,-1]</
{{out}}<pre>3</pre>
=={{header|Elena}}==
ELENA 5.0 :
<
import system'routines;
Line 1,089:
{
console.printLine(new int[]{1, 3, -5}.dotProduct(new int[]{4, -2, -1}))
}</
{{out}}
<pre>
Line 1,097:
=={{header|Elixir}}==
{{trans|Erlang}}
<
def dot_product(a,b) when length(a)==length(b), do: dot_product(a,b,0)
def dot_product(_,_) do
Line 1,107:
end
IO.puts Vector.dot_product([1,3,-5],[4,-2,-1])</
{{out}}
Line 1,116:
=={{header|Elm}}==
{{trans|Elm}}
<
dotp a b =
if List.length a /= List.length b then
Line 1,123:
Just (List.sum <| List.map2 (*) a b)
dotp [1,3,-5] [4,-2,-1])</
{{out}}
Line 1,131:
=={{header|Emacs Lisp}}==
<
(let ((res 0))
(dotimes (i (length v1))
Line 1,138:
(dot-product [1 2 3] [1 2 3]) ;=> 14
(dot-product '(1 2 3) '(1 2 3)) ;=> 14</
=={{header|Erlang}}==
<
dotProduct(_,_) -> erlang:error('Vectors must have the same length.').
Line 1,147:
dotProduct([],[],P) -> P.
dotProduct([1,3,-5],[4,-2,-1]).</
{{out}}<pre>3</pre>
=={{header|Euphoria}}==
<
atom sum
a *= b
Line 1,161:
end function
? dotprod({1,3,-5},{4,-2,-1})</
{{out}}
<pre>3</pre>
<
-- 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)</
{{out}}<pre>3</pre>
=={{header|F_Sharp|F#}}==
<
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</
<pre>> dot_product [| 1; 3; -5 |] [| 4; -2; -1 |] ;;
val it : int = 3</pre>
Line 1,180:
=={{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.
<
: dot-product ( u v -- w )
2dup [ length ] bi@ =
[ v. ] [ "Vector lengths must be equal" throw ] if ;</
( scratchpad ) { 1 3 -5 } { 4 -2 -1 } dot-product .
Line 1,190:
=={{header|FALSE}}==
<
3d: {Vectors' length}
1 3 5_ 4 2_ 1_ d;$1+ø@*p;!%. {Output: 3}</
=={{header|Fantom}}==
Dot product of lists of Int:
<
{
static Int dotProduct (Int[] a, Int[] b)
Line 1,215:
echo ("Dot product of $x and $y is ${dotProduct(x, y)}")
}
}</
=={{header|Forth}}==
<
: th cells + ;
Line 1,234:
-1 -2 4 b /vector vector!
a b /vector dotproduct . 3 ok</
=={{header|Fortran}}==
<
write (*, '(i0)') dot_product ([1, 3, -5], [4, -2, -1])
end program test_dot_product</
{{out}}<pre>3</pre>
Line 1,248:
=={{header|Frink}}==
<
{
if length[v1] != length[v2]
Line 1,257:
return sum[map[{|c1,c2| c1 * c2}, zip[v1, v2]]]
}</
=={{header|FunL}}==
<
def dot( a, b )
Line 1,266:
| otherwise = error( "Vector sizes must match" )
println( dot([1, 3, -5], [4, -2, -1]) )</
{{out}}<pre>3</pre>
=={{header|FreeBASIC}}==
<
function dot( a() as double, b() as double ) as double
Line 1,294:
print " zero3d dot x = ", dot(zero3d(), x())
print " z dot z = ", dot(z(), z())
print " y dot z = ", dot(y(), z())</
{{out}}
<pre>
Line 1,312:
=={{header|GAP}}==
<
[1, 3, -5]*[4, -2, -1];
# 3</
=={{header|GLSL}}==
The dot product is built-in:
<
float dot_product = dot(vec3(1, 3, -5), vec3(4, -2, -1));
</syntaxhighlight>
=={{header|Go}}==
===Implementation===
<
import (
Line 1,354:
}
fmt.Println(d)
}</
{{out}}
<pre>
Line 1,360:
</pre>
===Library gonum/floats===
<
import (
Line 1,375:
func main() {
fmt.Println(floats.Dot(v1, v2))
}</
{{out}}
<pre>
Line 1,383:
=={{header|Groovy}}==
Solution:
<
assert x && y && x.size() == y.size()
[x, y].transpose().collect{ xx, yy -> xx * yy }.sum()
}</
Test:
<
{{out}}<pre>3</pre>
=={{header|Haskell}}==
<
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</
Or, using the Maybe monad to avoid exceptions and keep things composable:
<
:: Num a
=> [a] -> [a] -> Maybe a
Line 1,414:
=> Maybe a -> IO ()
mbPrint (Just x) = print x
mbPrint n = print n</
=={{header|Hoon}}==
<
=| sum=@sd
|-
?: |(?=(~ a) ?=(~ b)) sum
$(a t.a, b t.b, sum (sum:si sum (pro:si i.a i.b)))</
=={{header|Hy}}==
<
(assert (= (len a) (len b)))
(sum (genexpr (* aterm bterm)
[(, aterm bterm) (zip a b)])))
(assert (= 3 (dotp [1 3 -5] [4 -2 -1])))</
=={{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.
<
write("a dot b := ",dotproduct([1, 3, -5],[4, -2, -1]))
end
Line 1,441:
every (dp := 0) +:= a[i := 1 to *a] * b[i]
return dp
end</
=={{header|IDL}}==
<syntaxhighlight lang="idl">
a = [1, 3, -5]
b = [4, -2, -1]
c = a#TRANSPOSE(b)
c = TOTAL(a*b,/PRESERVE_TYPE)
</syntaxhighlight>
=={{header|Idris}}==
<
import Data.Vect
Line 1,461:
main : IO ()
main = printLn $ dotProduct [1,2,3] [1,2,3]
</syntaxhighlight>
=={{header|J}}==
<
3
dotp=: +/ . * NB. Or defined as a verb (function)
1 3 _5 dotp 4 _2 _1
3</
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:
=={{header|Java}}==
<
public static void main(String[] args) {
Line 1,493:
return sum;
}
}</
{{out}}<pre>3.0</pre>
=={{header|JavaScript}}==
===ES5===
<
if (ary1.length != ary2.length)
throw "can't find dot product: arrays have different lengths";
Line 1,508:
print(dot_product([1,3,-5],[4,-2,-1])); // ==> 3
print(dot_product([1,3,-5],[4,-2,-1,0])); // ==> exception</
We could also use map and reduce in lieu of iteration,
<
function dotp_sum(a,b) { return a + b; }
function dotp_times(a,i) { return x[i] * y[i]; }
Line 1,521:
dotp([1,3,-5],[4,-2,-1]); // ==> 3
dotp([1,3,-5],[4,-2,-1,0]); // ==> exception</
===ES6===
Composing functional primitives into a '''dotProduct()''' which returns '''undefined''' (rather than an error) when the array lengths are unmatched.
<
'use strict';
Line 1,546:
return dotProduct([1, 3, -5], [4, -2, -1]);
})();</
{{Out}}
<syntaxhighlight lang="javascript">3</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">
def dot(x; y):
reduce range(0;x|length) as $i (0; . + x[$i] * y[$i]);
</syntaxhighlight>
Suppose however that we are given an array of objects, each of which has an "x" field and a "y" field,
Line 1,562:
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:<
Given the array of objects as input, the dot-product is then simply <code>SIGMA( .x * .y )</code>.
Example:<
[ {"x": 1, "y": 4}, {"x": 3, "y": -2}, {"x": -5, "y": -1} ]
| SIGMA( .x * .y ) # => 3</
=={{header|Jsish}}==
From Javascript ES5 imperative entry.
<
function dot_product(ary1, ary2) {
if (ary1.length != ary2.length) throw "can't find dot product: arrays have different lengths";
Line 1,589:
PASS!: err = can't find dot product: arrays have different lengths
=!EXPECTEND!=
*/</
{{out}}
Line 1,602:
=={{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]]).
<
y = [4, -2, -1]
z = dot(x, y)
z = x'*y
z = x ⋅ y</
=={{header|K}}==
<
3
1 3 -5 _dot 4 -2 -1
3</
=={{header|Klingphix}}==
<syntaxhighlight lang="text">:sq_mul
%c %i
( ) !c
Line 1,639:
pstack
" " input</
=={{header|Kotlin}}==
{{works with|Kotlin|1.0+}}
<
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) }
}</
{{out}}
<pre>3.0</pre>
=={{header|Lambdatalk}}==
<
{def dotp
{def dotp.r
Line 1,672:
{dotp {A.new 1 3 -5} {A.new 4 -2 -1}}
-> 3
</syntaxhighlight>
=={{header|LFE}}==
<
(: lists foldl #'+/2 0
(: lists zipwith #'*/2 a b)))
</syntaxhighlight>
=={{header|Liberty BASIC}}==
<
vectorB$ = "4, -2, -1"
print "DotProduct of ";vectorA$;" and "; vectorB$;" is ";
Line 1,704:
i = i+1
wend
end function </
=={{header|LLVM}}==
<
; 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,791:
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" }</
{{out}}
<pre>3</pre>
=={{header|Logo}}==
<
output apply "sum (map "product :a :b)
end
show dotprod [1 3 -5] [4 -2 -1] ; 3</
=={{header|Logtalk}}==
<
dot_product(A, B, 0, Sum).
Line 1,809:
dot_product([A| As], [B| Bs], Acc, Sum) :-
Acc2 is Acc + A*B,
dot_product(As, Bs, Acc2, Sum).</
=={{header|Lua}}==
<
local ret = 0
for i = 1, #a do
Line 1,820:
end
print(dotprod({1, 3, -5}, {4, -2, 1}))</
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module dot_product {
A=(1,3,-5)
Line 1,838:
}
Module dot_product
</syntaxhighlight>
=={{header|Maple}}==
Between Arrays, Vectors, or Matrices you can use the dot operator:
<
<
Between any of the above or lists, you can use the <code>LinearAlgebra[DotProduct]</code> function:
<
<
<
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
=={{header|MATLAB}}==
The dot product operation is a built-in function that operates on vectors of arbitrary length.
<
B = [4 -2 -1]
C = dot(A,B)</
For the Octave implimentation:
<
C = sum( A.*B );
end</
=={{header|Maxima}}==
<
/* 3 */</
=={{header|Mercury}}==
This will cause a software_error/1 exception if the lists are of different lengths.
<
:- interface.
Line 1,885:
dot_product(As, Bs) =
list.foldl_corresponding((func(A, B, Acc) = Acc + A * B), As, Bs, 0).</
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">С/П * ИП0 + П0 С/П БП 00</
''Input'': В/О x<sub>1</sub> С/П x<sub>2</sub> С/П y<sub>1</sub> С/П y<sub>2</sub> С/П ...
=={{header|Modula-2}}==
<
FROM RealStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 1,917:
ReadChar
END DotProduct.</
=={{header|MUMPS}}==
<
;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,928:
FOR I=1:1:$LENGTH(A,"^") SET SUM=SUM+($PIECE(A,"^",I)*$PIECE(B,"^",I))
KILL I
QUIT SUM</
=={{header|Nemerle}}==
This will cause an exception if the arrays are different lengths.
<
using System.Console;
using Nemerle.Collections.NCollectionsExtensions;
Line 1,948:
WriteLine(DotProduct(arr1, arr2));
}
}</
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols binary
Line 1,971:
method dotProduct(vecs = double[,]) public constant returns double signals IllegalArgumentException
return dotProduct(vecs[0], vecs[1])</
=={{header|newLISP}}==
<
(apply + (map * x y)))
(println (dot-product '(1 3 -5) '(4 -2 -1)))</
=={{header|Nim}}==
<
# Runtime error when a and b are differently sized seqs
proc dotp[T](a,b: T): int =
Line 1,988:
echo dotp([1,3,-5], [4,-2,-1])
echo dotp(@[1,2,3],@[4,5,6])</
Another version which allows to mix arrays and sequences provided they have the same length. It works also with miscellaneous number types (integers, floats).
<
func dotProduct[T](a, b: openArray[T]): T =
Line 2,001:
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])</
=={{header|Oberon-2}}==
{{Works with|oo2c version 2}}
<
MODULE DotProduct;
IMPORT
Line 2,031:
Out.Int(DotProduct(x,y),0);Out.Ln
END DotProduct.
</syntaxhighlight>
{{out}}
<pre>
Line 2,038:
=={{header|Objeck}}==
<
class DotProduct {
function : Main(args : String[]) ~ Nil {
Line 2,065:
}
}
}</
=={{header|Objective-C}}==
<
#import <stdint.h>
#import <stdlib.h>
Line 2,174:
}
return 0;
}</
=={{header|OCaml}}==
With lists:
<
(*
# dot [1.0; 3.0; -5.0] [4.0; -2.0; -1.0];;
- : float = 3.
*)</
With arrays:
<
if Array.length v <> Array.length u
then invalid_arg "Different array lengths";
Line 2,196:
# dot [| 1.0; 3.0; -5.0 |] [| 4.0; -2.0; -1.0 |];;
- : float = 3.
*)</
=={{header|Octave}}==
See [[Dot product#MATLAB]] for an implementation. If we have a row-vector and a column-vector, we can use simply *.
<
b = [4, -2, -1] % or [4; -2; -1] and avoid transposition with '
disp( a * b' ) % ' means transpose</
=={{header|Oforth}}==
<
{{out}}
Line 2,215:
=={{header|Ol}}==
<
(define (dot-product a b)
(apply + (map * a b)))
Line 2,221:
(print (dot-product '(1 3 -5) '(4 -2 -1)))
; ==> 3
</syntaxhighlight>
=={{header|Oz}}==
Vectors are represented as lists in this example.
<
fun {DotProduct Xs Ys}
{Length Xs} = {Length Ys} %% assert
Line 2,231:
end
in
{Show {DotProduct [1 3 ~5] [4 ~2 ~1]}}</
=={{header|PARI/GP}}==
<
sum(i=1,#u,u[i]*v[i])
};</
=={{header|Pascal}}==
Line 2,242:
=={{header|Perl}}==
<
{
my($vec_a, $vec_b) = @_;
Line 2,254:
my @vec_b = (4,-2,-1);
print dotprod(\@vec_a,\@vec_b), "\n"; # 3</
=={{header|Phix}}==
<!--<
<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>
<!--</
{{out}}
<pre>
Line 2,266:
=={{header|Phixmonti}}==
<
0 tolist var c
len for
Line 2,287:
sq_mul
sq_sum
pstack</
=={{header|PHP}}==
<
function dot_product($v1, $v2) {
if (count($v1) != count($v2))
Line 2,298:
echo dot_product(array(1, 3, -5), array(4, -2, -1)), "\n";
?></
=={{header|Picat}}==
<
L1 = [1, 3, -5],
L2 = [4, -2, -1],
Line 2,311:
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]). </
{{out}}
Line 2,318:
=={{header|PicoLisp}}==
<
(sum * A B) )
(dotProduct (1 3 -5) (4 -2 -1))</
{{out}}<pre>-> 3</pre>
=={{header|PL/I}}==
<
begin;
declare (A(n), B(n)) float;
Line 2,334:
dot_product = sum(a*b);
put (dot_product);
end;</
=={{header|Plain English}}==
<
Start up.
Make an example vector and another example vector.
Line 2,391:
Add 4 to the other example vector.
Add -2 to the other example vector.
Add -1 to the other example vector.</
{{out}}
<pre>
Line 2,398:
=={{header|PostScript}}==
<
/x exch def
/y exch def
Line 2,414:
-1 ==
}ifelse
}def</
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function dotproduct( $a, $b) {
$a | foreach -Begin {$i = $res = 0} -Process { $res += $_*$b[$i++] } -End{$res}
Line 2,423:
dotproduct (1..2) (1..2)
dotproduct (1..10) (11..20)
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 2,432:
=={{header|Prolog}}==
Works with SWI-Prolog.
<
maplist(mult, L1, L2, P),
sumlist(P, N).
mult(A,B,C) :-
C is A*B.</
Example :
<pre> ?- dot_product([1,3,-5], [4,-2,-1], N).
Line 2,443:
=={{header|PureBasic}}==
<
Protected i, sum, length = ArraySize(a())
Line 2,466:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
=={{header|Python}}==
<
assert len(a) == len(b), 'Vector sizes must match'
return sum(aterm * bterm for aterm,bterm in zip(a, b))
Line 2,475:
if __name__ == '__main__':
a, b = [1, 3, -5], [4, -2, -1]
assert dotp(a,b) == 3</
Line 2,484:
{{Works with|Python|3.7}}
<
from operator import (mul)
Line 2,574:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>Dot product of other vectors with [1, 3, -5]:
Line 2,586:
{{works with|QBasic|1.1}}
{{trans|FreeBASIC}}
<
zero3d(0) = 0!: zero3d(1) = 0!: zero3d(2) = 0!
DIM zero5d(4)
Line 2,610:
NEXT i
dot = dp
END FUNCTION</
=={{header|Quackery}}==
<
[ over i^ peek *
rot + swap ]
drop ] is .prod ( [ [ --> n )
' [ 1 3 -5 ] ' [ 4 -2 -1 ] .prod echo</
{{Out}}
Line 2,627:
=={{header|R}}==
Here are several ways to do the task.
<
y <- c(4, -2, -1)
Line 2,642:
}
dotp(x, y)</
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
(define (dot-product l r) (for/sum ([x l] [y r]) (* x y)))
Line 2,653:
;; dot-product works on sequences such as vectors:
(dot-product #(1 2 3) #(4 5 6))
</syntaxhighlight>
=={{header|Raku}}==
Line 2,659:
{{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"
=={{header|Rascal}}==
<
public int dotProduct(list[int] L, list[int] M){
Line 2,678:
throw "vector sizes must match";
}
}</
===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.
<
public real matrixDotproduct(rel[real x, real y, real v] column1, rel[real x, real y, real v] column2){
Line 2,693:
<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>
};</
=={{header|REBOL}}==
<
a: [1 3 -5]
Line 2,712:
]
dot-product a b</
=={{header|REXX}}==
===no error checking===
<
vectorA = ' 1 3 -5 ' /*populate vector A with some numbers*/
vectorB = ' 4 -2 -1 ' /* " " B " " " */
Line 2,731:
$=$+word(A,j) * word(B,j) /* ··· and add the product to the sum.*/
end /*j*/
return $ /*return the sum to function's invoker.*/</
'''output''' using the default (internal) inputs:
<pre>
Line 2,741:
===with error checking===
<
vectorA = ' 1 3 -5 ' /*populate vector A with some numbers*/
vectorB = ' 4 -2 -1 ' /* " " B " " " */
Line 2,770:
$=$ + #.1 * #.2 /* ··· and add the product to the sum.*/
end /*j*/
return $ /*return the sum to function's invoker.*/</
'''output''' is the same as the 1<sup>st</sup> REXX version. <br><br>
=={{header|Ring}}==
<
aVector = [2, 3, 5]
bVector = [4, 2, 1]
Line 2,785:
next
return sum
</syntaxhighlight>
=={{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:
<
y = rand(1,10);
s = sum( x .* y );</
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,800:
=={{header|RPL}}==
Being a language for a calculator, RPL makes this easy.
<syntaxhighlight lang="rpl"><<
[ 1 3 -5 ]
[ 4 -2 -1 ]
DOT
>></
=={{header|Ruby}}==
With the '''standard library''', require 'matrix' and call Vector#inner_product.
<
=> true
irb(main):002:0> Vector[1, 3, -5].inner_product Vector[4, -2, -1]
=> 3</
Or '''implement''' dot product.
<
def dot_product(other)
raise "not the same size!" if self.length != other.length
Line 2,820:
end
p [1, 3, -5].dot_product [4, -2, -1] # => 3</
=={{header|Run BASIC}}==
<
v2$ = "4, -2, -1"
Line 2,836:
dotProduct = dotProduct + val(v1$) * val(v2$)
wend
end function</
=={{header|Rust}}==
Implemented as a simple function with check for equal length of vectors.
<
// but using slices is more general and rustic
fn dot_product(a: &[i32], b: &[i32]) -> Option<i32> {
Line 2,857:
println!("{}", dot_product(&v1, &v2).unwrap());
}</
Line 2,863:
'''Uses an unstable feature.'''
<
use std::ops::{Add, Mul};
use std::num::Zero;
Line 2,891:
println!("{}", dot_product(&v1, &v2).unwrap());
}</
=={{header|S-lang}}==
<
{{out}}
<pre>3.0</pre>
Line 2,902:
=={{header|Sather}}==
Built-in class VEC "implements" euclidean (geometric) vectors.
<
main is
x ::= #VEC(|1.0, 3.0, -5.0|);
Line 2,908:
#OUT + x.dot(y) + "\n";
end;
end;</
=={{header|Scala}}==
{{libheader|Scala}}<
import n._ // import * operator
def dot(v2: Seq[T]) = {
Line 2,925:
val v2 = List(4, -2, -1)
println(v1 dot v2)
}</
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^5</math>RS}}
<
(apply + (map * a b)))
(display (dot-product '(1 3 -5) '(4 -2 -1)))
(newline)</
{{out}}<pre>3</pre>
=={{header|Scilab}}==
<
B = [4 -2 -1]
C = sum(A.*B)</
=={{header|Seed7}}==
<
$ syntax expr: .().dot.() is -> 6; # priority of dot operator
Line 2,964:
begin
writeln([](1, 3, -5) dot [](4, -2, -1));
end func;</
=={{header|Sidef}}==
<
(a »*« b)«+»;
};
say dot_product([1,3,-5], [4,-2,-1]); # => 3</
=={{header|Slate}}==
<
"Dot-product."
[
(0 below: (v size min: w size)) inject: 0 into:
[| :sum :index | sum + ((v at: index) * (w at: index))]
].</
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<
[
* anotherArray [
Line 2,993:
]
( #(1 3 -5) * #(4 -2 -1 ) ) printNl.</
=={{header|SNOBOL4}}==
<
dotp i = 1; sum = 0
loop sum = sum + (a<i> * b<i>)
Line 3,006:
b = array(3); b<1> = 4; b<2> = -2; b<3> = -1;
output = dotp(a,b)
end</
=={{header|SPARK}}==
Line 3,014:
The precondition enforces equality of the ranges of the two vectors.
<
--# inherit Spark_IO;
--# main_program;
Line 3,054:
Width => 6,
Base => 10);
end Dot_Product_Main;</
{{out}}<pre> 3</pre>
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:
<
from A inner join B on A.j=B.j
group by i, k</
=={{header|Standard ML}}==
With lists:
<
(*
- dot ([1.0, 3.0, ~5.0], [4.0, ~2.0, ~1.0]);
val it = 3.0 : real
*)</
With vectors:
<
if Vector.length v <> Vector.length u then
raise ListPair.UnequalLengths
Line 3,087:
- dot (#[1.0, 3.0, ~5.0], #[4.0, ~2.0, ~1.0]);
val it = 3.0 : real
*)</
=={{header|Stata}}==
With row vectors:
<
matrix b=4,-2,-1
matrix c=a*b'
di el("c",1,1)</
With column vectors:
<
matrix b=4\-2\-1
matrix c=a'*b
di el("c",1,1)</
=== Mata ===
With row vectors:
<
b=4,-2,-1
a*b'</
With column vectors:
<
b=4\-2\-1
a'*b</
In both cases, one cas also write
<syntaxhighlight lang
=={{header|Swift}}==
{{works with|Swift|1.2+}}
<
return reduce(lazy(zip(v1, v2)).map(*), 0, +)
}
println(dot([1, 3, -5], [4, -2, -1]))</
{{out}}
<pre>3.0</pre>
Line 3,133:
=={{header|Tcl}}==
{{tcllib|math::linearalgebra}}
<
set a {1 3 -5}
Line 3,139:
set dotp [::math::linearalgebra::dotproduct $a $b]
proc pp vec {return \[[join $vec ,]\]}
puts "[pp $a] \u2219 [pp $b] = $dotp"</
{{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).
<
{{out}}
<pre>
Line 3,160:
=={{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.
<
dot = sum:-0+ product*p
Line 3,166:
#cast %z
test = dot(<1,3,-5>,<4,-2,-1>)</
{{out}}<pre>3</pre>
=={{header|VBA}}==
<
dot_product = WorksheetFunction.SumProduct(x, y)
End Function
Line 3,176:
Public Sub main()
Debug.Print dot_product([{1,3,-5}], [{4,-2,-1}])
End Sub</
<pre> 3</pre>
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
WScript.Echo DotProduct("1,3,-5","4,-2,-1")
Line 3,195:
Next
End Function
</syntaxhighlight>
{{Out}}
Line 3,202:
=={{header|Visual Basic}}==
{{works with|Visual Basic|6}}
<
Function DotProduct(a() As Long, b() As Long) As Long
Line 3,245:
Debug.Assert Err.Description = "invalid input"
End Sub
</syntaxhighlight>
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Function DotProduct(a As Decimal(), b As Decimal()) As Decimal
Line 3,260:
End Sub
End Module</
{{out}}
<pre>3</pre>
=={{header|Vlang}}==
<
if x.len != y.len {
return error("incompatible lengths")
Line 3,280:
println(d)
}</
{{out}}
Line 3,288:
=={{header|Wart}}==
<
(sum+map (*) x y)</
<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:
=={{header|Wren}}==
<
construct new(a) {
if (a.type != List || a.count == 0 || !a.all { |i| i is Num }) {
Line 3,322:
var v2 = Vector.new([4, -2, -1])
System.print("The dot product of %(v1) and %(v2) is %(v1.dot(v2)).")</
{{out}}
Line 3,331:
=={{header|X86 Assembly}}==
Using FASM. Targets x64 Microsoft Windows.
<
entry start
Line 3,400:
import msvcrt,\
printf, 'printf'</
{{out}}<syntaxhighlight lang="text">3
Size mismatch; can't calculate.
0</
=={{header|XPL0}}==
<
func DotProd(U, V, L);
Line 3,418:
[IntOut(0, DotProd([1, 3, -5], [4, -2, -1], 3));
CrLf(0);
]</
{{out}}<pre>3</pre>
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">
sub sq_mul(a(), b(), c())
local n, i
Line 3,451:
print sq_sum(c())
</syntaxhighlight>
=={{header|Zig}}==
<
const Vector = std.meta.Vector;
Line 3,463:
try std.io.getStdOut().writer().print("{d}\n", .{dot});
}</
=={{header|zkl}}==
<
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
<
Utils.zipWith('*,a,b).sum()
}</
=={{header|ZX Spectrum Basic}}==
<
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</
[[Category:Geometry]]
|