How to resolve the algorithm Dot product step by step in the Nim programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Dot product step by step in the Nim programming language

Table of Contents

Problem Statement

Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length.

As an example, compute the dot product of the vectors:

If implementing the dot product of two vectors directly:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Dot product step by step in the Nim programming language

Source code in the nim programming language

# 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 =
  doAssert a.len == b.len
  for i in a.low..a.high:
    result += a[i] * b[i]

echo dotp([1,3,-5], [4,-2,-1])
echo dotp(@[1,2,3],@[4,5,6])


# Runtime error if lengths of arrays or sequences differ.

func dotProduct[T](a, b: openArray[T]): T =
  doAssert a.len == b.len
  for i in 0..a.high:
    result += a[i] * b[i]

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


  

You may also check:How to resolve the algorithm Horner's rule for polynomial evaluation step by step in the Octave programming language
You may also check:How to resolve the algorithm Eban numbers step by step in the C# programming language
You may also check:How to resolve the algorithm 100 doors step by step in the Lasso programming language
You may also check:How to resolve the algorithm Function composition step by step in the FunL programming language
You may also check:How to resolve the algorithm Arrays step by step in the Io programming language