Dot product: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(→‎{{header|Ruby}}: use sum method)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(24 intermediate revisions by 14 users not shown)
Line 276:
end.
</syntaxhighlight>
 
=={{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}}==
Line 864 ⟶ 916:
{{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}}==
Line 1,012 ⟶ 1,079:
{{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}}==
Line 1,363 ⟶ 1,441:
=={{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'''
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.
 
Dot product is intrinsically supported in Fōrmulæ.
In '''[https://formulae.org/?example=Dot_product this]''' page you can see the program(s) related to this task and their results.
 
'''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:
 
[[File:Fōrmulæ - Dot product 07.png]]
 
=={{header|GAP}}==
Line 1,458 ⟶ 1,556:
 
Or, using the Maybe monad to avoid exceptions and keep things composable:
<syntaxhighlight lang="haskell">dotpdotProduct :: Num a => [a] -> [a] -> Maybe a
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</syntaxhighlight>
 
=={{header|Hoon}}==
Line 1,530 ⟶ 1,625:
 
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}}==
Line 1,582 ⟶ 1,688:
 
===ES6===
Composing functional primitives into a '''dotProduct()''' which returns a '''undefinednull''' value (rather than an error) when the array lengths are unmatched.
 
<syntaxhighlight lang="javascript">(() => {
'"use strict'";
 
// ------------------- DOT PRODUCT -------------------
// dotProduct :: [Int] -> [Int] -> Int
 
const dotProduct = (xs, ys) => {
// dotProduct :: [Num] -> [Num] -> Either Null Num
const sum = xs => xs ? xs.reduce((a, b) => a + b, 0) : undefined;
const dotProduct = xs =>
ys => xs.length === ys.length
? sum(zipWith(mul)(xs)(ys))
: null;
 
 
// ---------------------- TEST -----------------------
 
// main :: IO ()
const main = () =>
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);
 
return xs.length === ys.length ? (
sum(zipWith((a, b) => a * b, xs, ys))
) : undefined;
}
 
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = (f, xs, ys) => {
// A list constructed by zipping with a
const ny = ys.length;
// custom function, rather than with the
return (xs.length <= ny ? xs : xs.slice(0, ny))
// default tuple constructor.
.map((x, i) => f(x, ys[i]));
xs => ys => xs.map(
}
(x, i) => f(x)(ys[i])
).slice(
0, Math.min(xs.length, ys.length)
);
 
// MAIN ---
return dotProduct([1, 3, -5], [4, -2, -1]);
return main();
})();</syntaxhighlight>
 
{{Out}}
<syntaxhighlight lang="javascript">3</syntaxhighlight>
 
=={{header|jq}}==
Line 1,881 ⟶ 2,009:
 
=={{header|M2000 Interpreter}}==
Version 12 can use types for arrays (earlier versions use variant type by default).
 
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 {
Line 1,888 ⟶ 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
Line 2,295 ⟶ 2,435:
sum(i=1,#u,u[i]*v[i])
};</syntaxhighlight>
 
===Alternative===
<syntaxhighlight lang="parigp">dot(u,v) = u * v~;</syntaxhighlight>
 
=={{header|Pascal}}==
Line 2,775 ⟶ 2,918:
 
=={{header|REXX}}==
===noWith error checking===
<syntaxhighlight 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.*/</syntaxhighlight>
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,797 ⟶ 2,955:
vector B = 4 -2 -1
 
dot product = 3</pre>
</pre>
 
===with error checking===
<syntaxhighlight lang="rexx">/*REXX program computes the dot product of two equal size vectors (of any size).*/
vectorA = ' 1 3 -5 ' /*populate vector A with some numbers*/
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.*/</syntaxhighlight>
'''output''' &nbsp; is the same as the 1<sup>st</sup> REXX version. <br><br>
 
=={{header|Ring}}==
Line 2,860 ⟶ 2,984:
=={{header|RPL}}==
Being a language for a calculator, RPL makes this easy.
<syntaxhighlight lang="rpl"><<
[ 1 3 -5 ]
[ 4 -2 -1 ]
DOT
>></syntaxhighlight>
 
=={{header|Ruby}}==
Line 3,067 ⟶ 3,189:
output = dotp(a,b)
end</syntaxhighlight>
 
=={{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 3,217 ⟶ 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}}==
Line 3,325 ⟶ 3,543:
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">fn dot(x []int, y []int) ?int {
fn dot(x []int, y []int) !int {
if x.len != y.len {
return error("incompatible lengths")
Line 3,337 ⟶ 3,556:
fn main() {
d := dot([1, 3, -5], [4, -2, -1])?!
 
println(d)
}
}</syntaxhighlight>
</syntaxhighlight>
 
{{out}}
Line 3,356 ⟶ 3,576:
 
=={{header|Wren}}==
<syntaxhighlight lang="ecmascriptwren">class Vector {
construct new(a) {
if (a.type != List || a.count == 0 || !a.all { |i| i is Num }) {
Line 3,387 ⟶ 3,607:
<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>
 
9,476

edits