Dot product: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎Tcl: Added implementation)
Line 27: Line 27:
dotp(a,b)
dotp(a,b)
assert dotp(a,b) == 3</lang>
assert dotp(a,b) == 3</lang>

=={{header|Tcl}}==
{{libheader|tcllib}}
<lang tcl>package require math::linearalgebra

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

Revision as of 09:16, 24 February 2010

Task
Dot product
You are encouraged to solve this task according to the task description, using any language you may know.

Create a function/use an in-built function, to compute the dot product, also known as the scaler product of two vectors.
If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors [1, 3, -5] and [4, -2, -1].

To calculate the dot product of two vectors, each vector must be the same length; multiply corresponding terms from each vector then sum the results to produce the answer:

Haskell

<lang 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</lang>

J

<lang j> 1 3 _5 +/ . * 4 _2 _1 3

  dotp=: +/ . *    NB. define as a function
  1 3 _5  dotp 4 _2 _1

3</lang> Applies generally to matricies and arrays of higher dimensions and can be used with verbs/functions other than product and sum.

Python

<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))

if __name__ == '__main__':

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

Tcl

Library: tcllib

<lang tcl>package require math::linearalgebra

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

[1,3,-5] ∙ [4,-2,-1] = 3.0