Vector products: Difference between revisions

PascalABC.NET
(→‎{{header|AutoHotkey}}: Created AutoHotkey entry)
(PascalABC.NET)
 
(148 intermediate revisions by 77 users not shown)
Line 1:
{{task}}
Define a vector having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z). If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.
 
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z).
Given vectors <code>A = (a<sub>1</sub>, a<sub>2</sub>, a<sub>3</sub>); B = (b<sub>1</sub>, b<sub>2</sub>, b<sub>3</sub>);</code> and <code>C = (c<sub>1</sub>, c<sub>2</sub>, c<sub>3</sub>);</code> then the following common vector products are defined:
* '''The dot product'''
: A • B = <code>a<sub>1</sub>b<sub>1</sub> + a<sub>2</sub>b<sub>2</sub> + a<sub>3</sub>b<sub>3</sub>;</code> a scalar quantity
* '''The cross product'''
: A x B = <code>(a<sub>2</sub>b<sub>3</sub> - a<sub>3</sub>b<sub>2</sub>, a<sub>3</sub>b<sub>1</sub> - a<sub>1</sub>b<sub>3</sub>, a<sub>1</sub>b<sub>2</sub> - a<sub>2</sub>b<sub>1</sub>);</code> a vector quantity
* '''The scalar triple product'''
: A • (B x C); a scalar quantity
* '''The vector triple product'''
: A x (B x C); a vector quantity
 
If you imagine a graph with the &nbsp; '''x''' &nbsp; and &nbsp; '''y''' &nbsp; axis being at right angles to each other and having a third, &nbsp; '''z''' &nbsp; axis coming out of the page, then a triplet of numbers, &nbsp; (X, Y, Z) &nbsp; would represent a point in the region, &nbsp; and a vector from the origin to the point.
;Task description
 
Given the three vectors: <code>a = (3, 4, 5); b = (4, 3, 5); c = (-5, -12, -13)</code>:
Given the vectors:
<big> A = (a<sub>1</sub>, a<sub>2</sub>, a<sub>3</sub>) </big>
<big> B = (b<sub>1</sub>, b<sub>2</sub>, b<sub>3</sub>) </big>
<big> C = (c<sub>1</sub>, c<sub>2</sub>, c<sub>3</sub>) </big>
then the following common vector products are defined:
* '''The dot product''' &nbsp; &nbsp; &nbsp; (a scalar quantity)
:::: <big> A • B = a<sub>1</sub>b<sub>1</sub> &nbsp; + &nbsp; a<sub>2</sub>b<sub>2</sub> &nbsp; + &nbsp; a<sub>3</sub>b<sub>3</sub> </big>
* '''The cross product''' &nbsp; &nbsp; &nbsp; (a vector quantity)
:::: <big> A x B = (a<sub>2</sub>b<sub>3</sub>&nbsp; - &nbsp; a<sub>3</sub>b<sub>2</sub>, &nbsp; &nbsp; a<sub>3</sub>b<sub>1</sub> &nbsp; - &nbsp; a<sub>1</sub>b<sub>3</sub>, &nbsp; &nbsp; a<sub>1</sub>b<sub>2</sub> &nbsp; - &nbsp; a<sub>2</sub>b<sub>1</sub>) </big>
* '''The scalar triple product''' &nbsp; &nbsp; &nbsp; (a scalar quantity)
:::: <big> A • (B x C) </big>
* '''The vector triple product''' &nbsp; &nbsp; &nbsp; (a vector quantity)
:::: <big> A x (B x C) </big>
 
 
;Task:
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
# Create a named function/subroutine/method to compute the dot product of two vectors.
# Create a function to compute the cross product of two vectors.
Line 20 ⟶ 31:
# Compute and display: <code>a • b</code>
# Compute and display: <code>a x b</code>
# Compute and display: <code>a • (b x c)</code>, the scalerscalar triple product.
# Compute and display: <code>a x (b x c)</code>, the vector triple product.
 
 
;References:
* &nbsp; A starting page on Wolfram MathWorld is &nbsp; {{Wolfram|Vector|Multiplication}}.
* [[Dot product]] here on RC.
* &nbsp; Wikipedia &nbsp; [[wp:Dot product|dot product]].
* A starting page on Wolfram Mathworld is {{Wolfram|Vector|Mulitplication}}.
* Wikipedias&nbsp; [[wp:DotWikipedia product|dot product]],&nbsp; [[wp:Cross product|cross product]]. and [[wp:Triple product|triple product]] entries.
* &nbsp; Wikipedia &nbsp; [[wp:Triple product|triple product]].
 
 
;C.f.
;Related tasks:
* [[Quaternion type]]
* &nbsp; [[Dot product]]
* &nbsp; [[Quaternion type]]
<br><br>
 
=={{header|11l}}==
<syntaxhighlight lang="11l">F scalartriplep(a, b, c)
return dot(a, cross(b, c))
F vectortriplep(a, b, c)
return cross(a, cross(b, c))
V a = (3, 4, 5)
V b = (4, 3, 5)
V c = (-5, -12, -13)
 
print(‘a = #.; b = #.; c = #.’.format(a, b, c))
print(‘a . b = #.’.format(dot(a, b)))
print(‘a x b = #.’.format(cross(a,b)))
print(‘a . (b x c) = #.’.format(scalartriplep(a, b, c)))
print(‘a x (b x c) = #.’.format(vectortriplep(a, b, c)))</syntaxhighlight>
 
{{out}}
<pre>
a = (3, 4, 5); b = (4, 3, 5); c = (-5, -12, -13)
a . b = 49
a x b = (5, 5, -7)
a . (b x c) = 6
a x (b x c) = (-267, 204, -3)
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">TYPE Vector=[INT x,y,z]
 
PROC CreateVector(INT vx,vy,vz Vector POINTER v)
v.x=vx v.y=vy v.z=vz
RETURN
 
PROC PrintVector(Vector POINTER v)
PrintF("(%I,%I,%I)",v.x,v.y,v.z)
RETURN
 
INT FUNC DotProduct(Vector POINTER v1,v2)
INT res
 
res=v1.x*v2.x ;calculation split into parts
res==+v1.y*v2.y ;otherwise incorrect result
res==+v1.z*v2.z ;is returned
RETURN (res)
 
PROC CrossProduct(Vector POINTER v1,v2,res)
res.x=v1.y*v2.z ;calculation split into parts
res.x==-v1.z*v2.y ;otherwise incorrect result
res.y=v1.z*v2.x ;is returned
res.y==-v1.x*v2.z
res.z=v1.x*v2.y
res.z==-v1.y*v2.x
RETURN
 
PROC Main()
Vector a,b,c,d,e
INT res
 
CreateVector(3,4,5,a)
CreateVector(4,3,5,b)
CreateVector(-5,-12,-13,c)
 
Print("a=") PrintVector(a) PutE()
Print("b=") PrintVector(b) PutE()
Print("c=") PrintVector(c) PutE()
PutE()
res=DotProduct(a,b)
PrintF("a.b=%I%E",res)
 
CrossProduct(a,b,d)
Print("axb=") PrintVector(d) PutE()
 
CrossProduct(b,c,d)
res=DotProduct(a,d)
PrintF("a.(bxc)=%I%E",res)
 
CrossProduct(b,c,d)
CrossProduct(a,d,e)
Print("ax(bxc)=") PrintVector(e) PutE()
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Vector_products.png Screenshot from Atari 8-bit computer]
<pre>
a=(3,4,5)
b=(4,3,5)
c=(-5,-12,-13)
 
a.b=49
axb=(5,5,-7)
a.(bxc)=6
ax(bxc)=(-267,204,-3)
</pre>
 
=={{header|Ada}}==
Line 37 ⟶ 147:
 
vector.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Vector is
Line 114 ⟶ 224:
Ada.Text_IO.Put ("A x (B x C) = "); Vector_Put (A * Float_Vector'(B * C));
Ada.Text_IO.New_Line;
end Vector;</langsyntaxhighlight>
Output:
<pre>A: ( 3.0, 4.0, 5.0)
Line 130 ⟶ 240:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
<langsyntaxhighlight lang="algol68">MODE FIELD = INT;
FORMAT field fmt = $g(-0)$;
 
Line 182 ⟶ 292:
printf(($"a . (b x c) = "f(field fmt)l$, a DOT (b X c)));
printf(($"a x (b x c) = "f(vec fmt)l$, a X (b X c)))
)</langsyntaxhighlight>
Output:
<pre>
Line 197 ⟶ 307:
a x (b x c) = (-267, 204, -3)
</pre>
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">begin
% define the Vector record type %
record Vector( integer X, Y, Z );
 
% calculates the dot product of two Vectors %
integer procedure dotProduct( reference(Vector) value A, B ) ;
( X(A) * X(B) ) + ( Y(A) * Y(B) ) + ( Z(A) * Z(B) );
 
% calculates the cross product or two Vectors %
reference(Vector) procedure crossProduct( reference(Vector) value A, B ) ;
Vector( ( Y(A) * Z(B) ) - ( Z(A) * Y(B) )
, ( Z(A) * X(B) ) - ( X(A) * Z(B) )
, ( X(A) * Y(B) ) - ( Y(A) * X(B) )
);
 
% calculates the scaler triple product of two vectors %
integer procedure scalerTripleProduct( reference(Vector) value A, B, C ) ;
dotProduct( A, crossProduct( B, C ) );
 
% calculates the vector triple product of two vectors %
reference(Vector) procedure vectorTripleProduct( reference(Vector) value A, B, C ) ;
crossProduct( A, crossProduct( B, C ) );
 
% test the Vector routines %
begin
procedure writeonVector( reference(Vector) value v ) ;
writeon( "(", X(v), ", ", Y(v), ", ", Z(v), ")" );
 
Reference(Vector) a, b, c;
 
a := Vector( 3, 4, 5 );
b := Vector( 4, 3, 5 );
c := Vector( -5, -12, -13 );
 
i_w := 1; s_w := 0; % set output formatting %
 
write( " a: " ); writeonVector( a );
write( " b: " ); writeonVector( b );
write( " c: " ); writeonVector( c );
write( " a . b: ", dotProduct( a, b ) );
write( " a x b: " ); writeonVector( crossProduct( a, b ) );
write( "a . ( b x c ): ", scalerTripleProduct( a, b, c ) );
write( "a x ( b x c ): " ); writeonVector( vectorTripleProduct( a, b, c ) )
end
end.</syntaxhighlight>
{{out}}
<pre>
a: (3, 4, 5)
b: (4, 3, 5)
c: (-5, -12, -13)
a . b: 49
a x b: (5, 5, -7)
a . ( b x c ): 6
a x ( b x c ): (-267, 204, -3)
</pre>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">dot ← +.×
cross ← 1⌽(⊣×1⌽⊢)-⊢×1⌽⊣</syntaxhighlight>
{{out}}
<syntaxhighlight lang="apl"> a←3 4 5
b←4 3 5
c←¯5 ¯12 ¯13
a dot b
49
a cross b
5 5 ¯7
a dot b cross c
6
a cross b cross c
¯267 204 ¯3</syntaxhighlight>
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">--------------------- VECTOR PRODUCTS ---------------------
 
-- dotProduct :: Num a => [a] -> [a] -> Either String a
on dotProduct(xs, ys)
-- Dot product of two vectors of equal dimension.
if length of xs = length of ys then
|Right|(sum(zipWith(my mul, xs, ys)))
else
|Left|("Dot product not defined for vectors of differing dimension.")
end if
end dotProduct
 
 
-- crossProduct :: Num a => (a, a, a) -> (a, a, a)
-- Either String -> (a, a, a)
on crossProduct(xs, ys)
-- The cross product of two 3D vectors.
if 3 ≠ length of xs or 3 ≠ length of ys then
|Left|("Cross product is defined only for 3d vectors.")
else
set {x1, x2, x3} to xs
set {y1, y2, y3} to ys
|Right|({¬
x2 * y3 - x3 * y2, ¬
x3 * y1 - x1 * y3, ¬
x1 * y2 - x2 * y1})
end if
end crossProduct
 
 
-- scalarTriple :: Num a => (a, a, a) -> (a, a, a) -> (a, a a) ->
-- Either String -> a
on scalarTriple(q, r, s)
-- The scalar triple product.
script go
on |λ|(ys)
dotProduct(q, ys)
end |λ|
end script
bindLR(crossProduct(r, s), go)
end scalarTriple
 
 
-- vectorTriple :: Num a => (a, a, a) -> (a, a, a) -> (a, a a) ->
-- Either String -> (a, a, a)
on vectorTriple(q, r, s)
-- The vector triple product.
script go
on |λ|(ys)
crossProduct(q, ys)
end |λ|
end script
bindLR(crossProduct(r, s), go)
end vectorTriple
 
 
-------------------------- TEST ---------------------------
on run
set a to {3, 4, 5}
set b to {4, 3, 5}
set c to {-5, -12, -13}
set d to {3, 4, 5, 6}
script test
on |λ|(f)
either(my identity, my show, ¬
mReturn(f)'s |λ|(a, b, c, d))
end |λ|
end script
tell test
unlines({¬
"a . b = " & |λ|(dotProduct), ¬
"a x b = " & |λ|(crossProduct), ¬
"a . (b x c) = " & |λ|(scalarTriple), ¬
"a x (b x c) = " & |λ|(vectorTriple), ¬
"a x d = " & either(my identity, my show, ¬
dotProduct(a, d)), ¬
"a . (b x d) = " & either(my identity, my show, ¬
scalarTriple(a, b, d)) ¬
})
end tell
end run
 
 
-------------------- GENERIC FUNCTIONS --------------------
 
-- Left :: a -> Either a b
on |Left|(x)
{type:"Either", |Left|:x, |Right|:missing value}
end |Left|
 
 
-- Right :: b -> Either a b
on |Right|(x)
{type:"Either", |Left|:missing value, |Right|:x}
end |Right|
 
 
-- bindLR (>>=) :: Either a -> (a -> Either b) -> Either b
on bindLR(m, mf)
if missing value is not |Left| of m then
m
else
mReturn(mf)'s |λ|(|Right| of m)
end if
end bindLR
 
 
-- either :: (a -> c) -> (b -> c) -> Either a b -> c
on either(lf, rf, e)
if missing value is |Left| of e then
tell mReturn(rf) to |λ|(|Right| of e)
else
tell mReturn(lf) to |λ|(|Left| of e)
end if
end either
 
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
 
 
-- identity :: a -> a
on identity(x)
-- The argument unchanged.
x
end identity
 
 
-- intercalate :: String -> [String] -> String
on intercalate(delim, xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, delim}
set str to xs as text
set my text item delimiters to dlm
str
end intercalate
 
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of xs.
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
 
 
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
 
 
-- mul :: Num a :: a -> a -> a
on mul(x, y)
x * y
end mul
 
 
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
 
 
-- show :: a -> String
on show(x)
if list is class of x then
showList(x)
else
str(x)
end if
end show
 
 
-- showList :: [a] -> String
on showList(xs)
"[" & intercalate(", ", map(my str, xs)) & "]"
end showList
 
 
-- str :: a -> String
on str(x)
x as string
end str
 
 
-- sum :: [Number] -> Number
on sum(xs)
script add
on |λ|(a, b)
a + b
end |λ|
end script
foldl(add, 0, xs)
end sum
 
 
-- unlines :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation
-- of a list of strings with the newline character.
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set s to xs as text
set my text item delimiters to dlm
s
end unlines
 
 
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys)
end repeat
return lst
end tell
end zipWith</syntaxhighlight>
{{Out}}
<pre>a . b = 49
a x b = [5, 5, -7]
a . (b x c) = 6
a x (b x c) = [-267, 204, -3]
a x d = Dot product not defined for vectors of differing dimension.
a . (b x d) = Cross product is defined only for 3d vectors</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">; dot product
dot: function [a b][
sum map couple a b => product
]
 
; cross product
cross: function [a b][
A: (a\1 * b\2) - a\2 * b\1
B: (a\2 * b\0) - a\0 * b\2
C: (a\0 * b\1) - a\1 * b\0
@[A B C]
]
 
; scalar triple product
stp: function [a b c][
dot a cross b c
]
 
; vector triple product
vtp: function [a b c][
cross a cross b c
]
 
; task
a: [3 4 5]
b: [4 3 5]
c: @[neg 5 neg 12 neg 13]
 
print ["a • b =", dot a b]
print ["a x b =", cross a b]
print ["a • (b x c) =", stp a b c]
print ["a x (b x c) =", vtp a b c]</syntaxhighlight>
 
{{out}}
 
<pre>a • b = 49
a x b = [5 5 -7]
a • (b x c) = 6
a x (b x c) = [-267 204 -3]</pre>
 
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
<lang AutoHotkey>V := {a: [3, 4, 5], b: [4, 3, 5], c: [-5, -12, -13]}
<syntaxhighlight lang="autohotkey">V := {a: [3, 4, 5], b: [4, 3, 5], c: [-5, -12, -13]}
 
for key, val in V
Line 218 ⟶ 710:
CrossProduct(v1, v2) {
return, [v1[2] * v2[3] - v1[3] * v2[2]
, v1[3] * v2[1] - v1[1] * v2[3]
, v1[1] * v2[2] - v1[2] * v2[1]]
}
 
Line 228 ⟶ 720:
VectorTripleProduct(v1, v2, v3) {
return, CrossProduct(v1, CrossProduct(v2, v3))
}</langsyntaxhighlight>
'''Output:'''
<pre>a = (3, 4, 5)
Line 240 ⟶ 732:
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -f
BEGIN {
a[1] = 3; a[2]= 4; a[3] = 5;
Line 268 ⟶ 760:
function printVec(C) {
return "[ "C[1]" "C[2]" "C[3]" ]";
}</langsyntaxhighlight>
Output:
<pre>a = [ 3 4 5 ]
Line 281 ⟶ 773:
=={{header|BASIC256}}==
{{works with|BASIC256 }}
<langsyntaxhighlight lang="basic256">
a={3,4,5}:b={4,3,5}:c={-5,-12,-13}
 
Line 315 ⟶ 807:
end subroutine
 
</langsyntaxhighlight>
Output:
<pre>
Line 326 ⟶ 818:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> DIM a(2), b(2), c(2), d(2)
a() = 3, 4, 5
b() = 4, 3, 5
Line 356 ⟶ 848:
PROCcross(B(),C(),D())
PROCcross(A(),D(),D())
ENDPROC</langsyntaxhighlight>
Output:
<pre>
Line 364 ⟶ 856:
a x (b x c) = (-267, 204, -3)
</pre>
 
=={{header|BQN}}==
The cross product function here multiplies each vector pointwise by the other rotated by one. To align this result with the third index (the one not involved), it's rotated once more at the end. The APL solution <code>1⌽(⊣×1⌽⊢)-⊢×1⌽⊣</code> uses the same idea and works in BQN without modification.
<syntaxhighlight lang="bqn">Dot ← +´∘×
Cross ← 1⊸⌽⊸×{1⌽𝔽˜-𝔽}
Triple ← {𝕊a‿b‿c: a Dot b Cross c}
VTriple ← Cross´
 
a←3‿4‿5
b←4‿3‿5
c←¯5‿¯12‿¯13</syntaxhighlight>
 
Results:
<syntaxhighlight lang="bqn"> a Dot b
49
 
a Cross b
⟨ 5 5 ¯7 ⟩
 
Triple a‿b‿c
6
 
VTriple a‿b‿c
⟨ ¯267 204 ¯3 ⟩</syntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include<stdio.h>
 
typedef struct{
Line 412 ⟶ 928:
return 0;
}</langsyntaxhighlight>
Output:
<pre>
Line 425 ⟶ 941:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Windows.Media.Media3D;
 
Line 451 ⟶ 967:
Console.WriteLine(VectorTripleProduct(a, b, c));
}
}</langsyntaxhighlight>
Output:
<pre>49
Line 459 ⟶ 975:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
 
template< class T >
Line 512 ⟶ 1,028:
std::cout << "a x b x c : " << a.triplevec( b , c ) << "\n" ;
return 0 ;
}</langsyntaxhighlight>
Output:<PRE>a . b : 49
a x b : ( 5 , 5 , -7 )
Line 518 ⟶ 1,034:
a x b x c : ( -267 , 204 , -3 )
</PRE>
 
=={{header|Ceylon}}==
<syntaxhighlight lang="ceylon">shared void run() {
 
alias Vector => Float[3];
function dot(Vector a, Vector b) =>
a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
function cross(Vector a, Vector b) => [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0]
];
function scalarTriple(Vector a, Vector b, Vector c) =>
dot(a, cross(b, c));
function vectorTriple(Vector a, Vector b, Vector c) =>
cross(a, cross(b, c));
value a = [ 3.0, 4.0, 5.0 ];
value b = [ 4.0, 3.0, 5.0 ];
value c = [-5.0, -12.0, -13.0 ];
print("``a`` . ``b`` = ``dot(a, b)``");
print("``a`` X ``b`` = ``cross(a, b)``");
print("``a`` . ``b`` X ``c`` = ``scalarTriple(a, b, c)``");
print("``a`` X ``b`` X ``c`` = ``vectorTriple(a, b, c)``");
}</syntaxhighlight>
{{out}}
<pre>[3.0, 4.0, 5.0] . [4.0, 3.0, 5.0] = 49.0
[3.0, 4.0, 5.0] X [4.0, 3.0, 5.0] = [5.0, 5.0, -7.0]
[3.0, 4.0, 5.0] . [4.0, 3.0, 5.0] X [-5.0, -12.0, -13.0] = 6.0
[3.0, 4.0, 5.0] X [4.0, 3.0, 5.0] X [-5.0, -12.0, -13.0] = [-267.0, 204.0, -3.0]</pre>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defrecord Vector [x y z])
 
(defn dot
Line 544 ⟶ 1,095:
(dot a (cross b c))
(cross a (cross b c)))]
(println prod)))</langsyntaxhighlight>
Output:<PRE>
49
Line 550 ⟶ 1,101:
6
#:user.Vector{:x -267, :y 204, :z -3}</PRE>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">vector = cluster [T: type] is make, dot_product, cross_product,
equal, power, mul, unparse
where T has add: proctype (T,T) returns (T) signals (overflow),
sub: proctype (T,T) returns (T) signals (overflow),
mul: proctype (T,T) returns (T) signals (overflow),
equal: proctype (T,T) returns (bool),
unparse: proctype (T) returns (string)
rep = struct[x, y, z: T]
make = proc (x, y, z: T) returns (cvt)
return(rep${x:x, y:y, z:z})
end make
dot_product = proc (a, b: cvt) returns (T) signals (overflow)
return (a.x*b.x + a.y*b.y + a.z*b.z) resignal overflow
end dot_product
cross_product = proc (a, b: cvt) returns (cvt) signals (overflow)
begin
x: T := a.y * b.z - a.z * b.y
y: T := a.z * b.x - a.x * b.z
z: T := a.x * b.y - a.y * b.x
return(down(make(x,y,z)))
end resignal overflow
end cross_product
equal = proc (a, b: cvt) returns (bool)
return (a.x = b.x & a.y = b.y & a.z = b.z)
end equal
% Allow cross_product to be written as ** and dot_product to be written as *
power = proc (a, b: cvt) returns (cvt) signals (overflow)
return(down(cross_product(up(a),up(b)))) resignal overflow
end power
mul = proc (a, b: cvt) returns (T) signals (overflow)
return(dot_product(up(a),up(b))) resignal overflow
end mul
% Standard to_string routine. Properly, `parse' should also be defined,
% and x = parse(unparse(x)) forall x; but I'm not bothering here.
unparse = proc (v: cvt) returns (string)
return( "(" || T$unparse(v.x)
|| ", " || T$unparse(v.y)
|| ", " || T$unparse(v.z) || ")" )
end unparse
end vector
 
start_up = proc ()
vi = vector[int] % integer math is good enough for the examples
po: stream := stream$primary_output()
a, b, c: vi
a := vi$make(3, 4, 5)
b := vi$make(4, 3, 5)
c := vi$make(-5, -12, -13)
stream$putl(po, " a = " || vi$unparse(a))
stream$putl(po, " b = " || vi$unparse(b))
stream$putl(po, " c = " || vi$unparse(c))
stream$putl(po, " a . b = " || int$unparse(a * b))
stream$putl(po, " a x b = " || vi$unparse(a ** b))
stream$putl(po, "a . (b x c) = " || int$unparse(a * b ** c))
stream$putl(po, "a x (b x c) = " || vi$unparse(a ** b ** c))
end start_up</syntaxhighlight>
{{out}}
<pre> a = (3, 4, 5)
b = (4, 3, 5)
c = (-5, -12, -13)
a . b = 49
a x b = (5, 5, -7)
a . (b x c) = 6
a x (b x c) = (-267, 204, -3)</pre>
 
=={{header|Common Lisp}}==
Line 555 ⟶ 1,183:
Using the Common Lisp Object System.
 
<langsyntaxhighlight lang="lisp">(defclass 3d-vector ()
((x :type number :initarg :x)
(y :type number :initarg :y)
Line 599 ⟶ 1,227:
(cross-product a b)
(scalar-triple-product a b c)
(vector-triple-product a b c))))</langsyntaxhighlight>
Output:
CL-USER> (vector-products-example)
Line 606 ⟶ 1,234:
6
#<3D-VECTOR -267 204 -3>
 
Using vector type
 
<syntaxhighlight lang="lisp">(defun cross (a b)
(when (and (equal (length a) 3) (equal (length b) 3))
(vector
(- (* (elt a 1) (elt b 2)) (* (elt a 2) (elt b 1)))
(- (* (elt a 2) (elt b 0)) (* (elt a 0) (elt b 2)))
(- (* (elt a 0) (elt b 1)) (* (elt a 1) (elt b 0))))))
 
(defun dot (a b)
(when (equal (length a) (length b))
(loop for ai across a for bi across b sum (* ai bi))))
 
(defun scalar-triple (a b c)
(dot a (cross b c)))
 
(defun vector-triple (a b c)
(cross a (cross b c)))
 
(defun task (a b c)
(values (dot a b)
(cross a b)
(scalar-triple a b c)
(vector-triple a b c)))
</syntaxhighlight>
 
Output:
CL-USER> (task (vector 3 4 5) (vector 4 3 5) (vector -5 -12 -13))
49
#(5 5 -7)
6
#(-267 204 -3)
 
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
 
record Vector is
x: int32; # Cowgol does not have floating point types,
y: int32; # but for the examples it does not matter.
z: int32;
end record;
 
sub print_signed(n: int32) is
if n < 0 then
print_char('-');
n := -n;
end if;
print_i32(n as uint32);
end sub;
 
sub print_vector(v: [Vector]) is
print_char('(');
print_signed(v.x);
print(", ");
print_signed(v.y);
print(", ");
print_signed(v.z);
print_char(')');
print_nl();
end sub;
 
sub dot(a: [Vector], b: [Vector]): (r: int32) is
r := a.x * b.x + a.y * b.y + a.z * b.z;
end sub;
 
# Unfortunately it is impossible to return a complex type
# from a function. We have to have the caller pass in a pointer
# and have this function set its fields.
sub cross(a: [Vector], b: [Vector], r: [Vector]) is
r.x := a.y * b.z - a.z * b.y;
r.y := a.z * b.x - a.x * b.z;
r.z := a.x * b.y - a.y * b.x;
end sub;
 
sub scalarTriple(a: [Vector], b: [Vector], c: [Vector]): (r: int32) is
var v: Vector;
cross(b, c, &v);
r := dot(a, &v);
end sub;
 
sub vectorTriple(a: [Vector], b: [Vector], c: [Vector], r: [Vector]) is
var v: Vector;
cross(b, c, &v);
cross(a, &v, r);
end sub;
 
var a: Vector := {3, 4, 5};
var b: Vector := {4, 3, 5};
var c: Vector := {-5, -12, -13};
var scratch: Vector;
 
print(" a = "); print_vector(&a);
print(" b = "); print_vector(&b);
print(" c = "); print_vector(&c);
print(" a . b = "); print_signed(dot(&a, &b)); print_nl();
print(" a x b = "); cross(&a, &b, &scratch); print_vector(&scratch);
print("a . b x c = "); print_signed(scalarTriple(&a, &b, &c)); print_nl();
print("a x b x c = "); vectorTriple(&a, &b, &c, &scratch);
print_vector(&scratch);</syntaxhighlight>
{{out}}
<pre> a = (3, 4, 5)
b = (4, 3, 5)
c = (-5, -12, -13)
a . b = 49
a x b = (5, 5, -7)
a . b x c = 6
a x b x c = (-267, 204, -3)</pre>
 
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">class Vector
property x, y, z
def initialize(@x : Int64, @y : Int64, @z : Int64) end
def dot_product(other : Vector)
(self.x * other.x) + (self.y * other.y) + (self.z * other.z)
end
def cross_product(other : Vector)
Vector.new(self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x)
end
def scalar_triple_product(b : Vector, c : Vector)
self.dot_product(b.cross_product(c))
end
def vector_triple_product(b : Vector, c : Vector)
self.cross_product(b.cross_product(c))
end
def to_s
"(#{self.x}, #{self.y}, #{self.z})\n"
end
end
 
a = Vector.new(3, 4, 5)
b = Vector.new(4, 3, 5)
c = Vector.new(-5, -12, -13)
puts "a = #{a.to_s}"
puts "b = #{b.to_s}"
puts "c = #{c.to_s}"
puts "a dot b = #{a.dot_product b}"
puts "a cross b = #{a.cross_product(b).to_s}"
puts "a dot (b cross c) = #{a.scalar_triple_product b, c}"
puts "a cross (b cross c) = #{a.vector_triple_product(b, c).to_s}"</syntaxhighlight>
{{out}}
<pre>a = (3, 4, 5)
b = (4, 3, 5)
c = (-5, -12, -13)
a dot b = 49
a cross b = (5, 5, -7)
a dot (b cross c) = 6
a cross (b cross c) = (-267, 204, -3)</pre>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.conv, std.numeric;
 
struct V3 {
union {
immutable static struct { double x, y, z; }
immutable double[3] v;
}
 
double dot(in V3 rhs) const pure nothrow /*@safe*/ const pure nothrow@nogc {
return dotProduct(v, rhs.v);
}
 
V3 cross(in V3 rhs) @safe const pure nothrow @safe @nogc {
return V3(y * rhs.z - z * rhs.y,
z * rhs.x - x * rhs.z,
Line 626 ⟶ 1,411:
}
 
string toString() /*@safe*/ const { return v.text(v); }
}
 
double scalarTriple(in V3 a, in V3 b, in V3 c) /*@safe*/ pure nothrow {
/*@safe*/ pure nothrow {
return a.dot(b.cross(c));
// function vector_products.V3.cross (const(V3) rhs) immutable
Line 636 ⟶ 1,420:
}
 
V3 vectorTriple(in V3 a, in V3 b, in V3 c) @safe pure nothrow @nogc {
return a.cross(b.cross(c));
}
Line 644 ⟶ 1,428:
b = {4, 3, 5},
c = {-5, -12, -13};
 
writeln("a = ", a);
writeln("b = ", b);
Line 651 ⟶ 1,436:
writeln("a . (b x c) = ", scalarTriple(a, b, c));
writeln("a x (b x c) = ", vectorTriple(a, b, c));
}</langsyntaxhighlight>
{{out}}
<pre>a = [3, 4, 5]
Line 660 ⟶ 1,445:
a . (b x c) = 6
a x (b x c) = [-267, 204, -3]</pre>
 
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Vector_products#Pascal Pascal].
 
=={{header|EasyLang}}==
<syntaxhighlight>
func vdot a[] b[] .
for i to len a[]
r += a[i] * b[i]
.
return r
.
func[] vcross a[] b[] .
r[] &= a[2] * b[3] - a[3] * b[2]
r[] &= a[3] * b[1] - a[1] * b[3]
r[] &= a[1] * b[2] - a[2] * b[1]
return r[]
.
a[] = [ 3 4 5 ]
b[] = [ 4 3 5 ]
c[] = [ -5 -12 -13 ]
#
print vdot a[] b[]
print vcross a[] b[]
print vdot a[] vcross b[] c[]
print vcross a[] vcross b[] c[]
</syntaxhighlight>
 
{{out}}
<pre>
49
[ 5 5 -7 ]
6
[ -267 204 -3 ]
</pre>
 
=={{header|EchoLisp}}==
The '''math''' library includes the '''dot-product''' and '''cross-product''' functions. They work on complex or real vectors.
<syntaxhighlight lang="scheme">
(lib 'math)
 
(define (scalar-triple-product a b c)
(dot-product a (cross-product b c)))
(define (vector-triple-product a b c)
(cross-product a (cross-product b c)))
 
(define a #(3 4 5))
(define b #(4 3 5))
(define c #(-5 -12 -13))
 
(cross-product a b)
→ #( 5 5 -7)
(dot-product a b)
→ 49
(scalar-triple-product a b c)
→ 6
(vector-triple-product a b c)
→ #( -267 204 -3)
</syntaxhighlight>
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">defmodule Vector do
def dot_product({a1,a2,a3}, {b1,b2,b3}), do: a1*b1 + a2*b2 + a3*b3
def cross_product({a1,a2,a3}, {b1,b2,b3}), do: {a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1}
def scalar_triple_product(a, b, c), do: dot_product(a, cross_product(b, c))
def vector_triple_product(a, b, c), do: cross_product(a, cross_product(b, c))
end
 
a = {3, 4, 5}
b = {4, 3, 5}
c = {-5, -12, -13}
 
IO.puts "a = #{inspect a}"
IO.puts "b = #{inspect b}"
IO.puts "c = #{inspect c}"
IO.puts "a . b = #{inspect Vector.dot_product(a, b)}"
IO.puts "a x b = #{inspect Vector.cross_product(a, b)}"
IO.puts "a . (b x c) = #{inspect Vector.scalar_triple_product(a, b, c)}"
IO.puts "a x (b x c) = #{inspect Vector.vector_triple_product(a, b, c)}"</syntaxhighlight>
 
{{out}}
<pre>
a = {3, 4, 5}
b = {4, 3, 5}
c = {-5, -12, -13}
a . b = 49
a x b = {5, 5, -7}
a . (b x c) = 6
a x (b x c) = {-267, 204, -3}
</pre>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module(vector).
-export([main/0]).
vector_product(X,Y)->
[X1,X2,X3]=X,
[Y1,Y2,Y3]=Y,
Ans=[X2*Y3-X3*Y2,X3*Y1-X1*Y3,X1*Y2-X2*Y1],
Ans.
dot_product(X,Y)->
[X1,X2,X3]=X,
[Y1,Y2,Y3]=Y,
Ans=X1*Y1+X2*Y2+X3*Y3,
io:fwrite("~p~n",[Ans]).
main()->
{ok, A} = io:fread("Enter vector A : ", "~d ~d ~d"),
{ok, B} = io:fread("Enter vector B : ", "~d ~d ~d"),
{ok, C} = io:fread("Enter vector C : ", "~d ~d ~d"),
dot_product(A,B),
Ans=vector_product(A,B),
io:fwrite("~p,~p,~p~n",Ans),
dot_product(C,vector_product(A,B)),
io:fwrite("~p,~p,~p~n",vector_product(C,vector_product(A,B))).
</syntaxhighlight>
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM VECTORPRODUCT
 
!$DOUBLE
 
TYPE TVECTOR=(X,Y,Z)
 
DIM A:TVECTOR,B:TVECTOR,C:TVECTOR
 
DIM AA:TVECTOR,BB:TVECTOR,CC:TVECTOR
DIM DD:TVECTOR,EE:TVECTOR,FF:TVECTOR
 
PROCEDURE DOTPRODUCT(DD.,EE.->DOTP)
DOTP=DD.X*EE.X+DD.Y*EE.Y+DD.Z*EE.Z
END PROCEDURE
 
PROCEDURE CROSSPRODUCT(DD.,EE.->FF.)
FF.X=DD.Y*EE.Z-DD.Z*EE.Y
FF.Y=DD.Z*EE.X-DD.X*EE.Z
FF.Z=DD.X*EE.Y-DD.Y*EE.X
END PROCEDURE
 
PROCEDURE SCALARTRIPLEPRODUCT(AA.,BB.,CC.->SCALARTP)
CROSSPRODUCT(BB.,CC.->FF.)
DOTPRODUCT(AA.,FF.->SCALARTP)
END PROCEDURE
 
PROCEDURE VECTORTRIPLEPRODUCT(AA.,BB.,CC.->FF.)
CROSSPRODUCT(BB.,CC.->FF.)
CROSSPRODUCT(AA.,FF.->FF.)
END PROCEDURE
 
PROCEDURE PRINTVECTOR(AA.)
PRINT("(";AA.X;",";AA.Y;",";AA.Z;")")
END PROCEDURE
 
BEGIN
A.X=3 A.Y=4 A.Z=5
B.X=4 B.Y=3 B.Z=5
C.X=-5 C.Y=-12 C.Z=-13
 
PRINT("A: ";) PRINTVECTOR(A.)
PRINT("B: ";) PRINTVECTOR(B.)
PRINT("C: ";) PRINTVECTOR(C.)
 
PRINT
DOTPRODUCT(A.,B.->DOTP)
PRINT("A.B =";DOTP)
 
CROSSPRODUCT(A.,B.->FF.)
PRINT("AxB =";) PRINTVECTOR(FF.)
 
SCALARTRIPLEPRODUCT(A.,B.,C.->SCALARTP)
PRINT("A.(BxC)=";SCALARTP)
 
VECTORTRIPLEPRODUCT(A.,B.,C.->FF.)
PRINT("Ax(BxC)=";) PRINTVECTOR(FF.)
END PROGRAM
</syntaxhighlight>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">constant X = 1, Y = 2, Z = 3
 
function dot_product(sequence a, sequence b)
Line 697 ⟶ 1,662:
? scalar_triple( a, b, c )
puts(1,"a x (b x c) = ")
? vector_triple( a, b, c )</langsyntaxhighlight>
Output:
<pre>a = {3,4,5}
Line 706 ⟶ 1,671:
a dot (b x c) = 6
a x (b x c) = {-267,204,-3}
</pre>
 
=={{header|F#|F sharp}}==
<syntaxhighlight lang="fsharp">let dot (ax, ay, az) (bx, by, bz) =
ax * bx + ay * by + az * bz
 
let cross (ax, ay, az) (bx, by, bz) =
(ay*bz - az*by, az*bx - ax*bz, ax*by - ay*bx)
 
let scalTrip a b c =
dot a (cross b c)
 
let vecTrip a b c =
cross a (cross b c)
 
[<EntryPoint>]
let main _ =
let a = (3.0, 4.0, 5.0)
let b = (4.0, 3.0, 5.0)
let c = (-5.0, -12.0, -13.0)
printfn "%A" (dot a b)
printfn "%A" (cross a b)
printfn "%A" (scalTrip a b c)
printfn "%A" (vecTrip a b c)
0 // return an integer exit code</syntaxhighlight>
{{out}}
<pre>49.0
(5.0, 5.0, -7.0)
6.0
(-267.0, 204.0, -3.0)</pre>
 
=={{header|Factor}}==
Factor has a fantastic <tt>math.vectors</tt> vocabulary, but in the spirit of the task, it is not used.
<syntaxhighlight lang="factor">USING: arrays io locals math prettyprint sequences ;
 
: dot-product ( a b -- dp ) [ * ] 2map sum ;
 
:: cross-product ( a b -- cp )
a first :> a1 a second :> a2 a third :> a3
b first :> b1 b second :> b2 b third :> b3
a2 b3 * a3 b2 * - ! X
a3 b1 * a1 b3 * - ! Y
a1 b2 * a2 b1 * - ! Z
3array ;
 
: scalar-triple-product ( a b c -- stp )
cross-product dot-product ;
 
: vector-triple-product ( a b c -- vtp )
cross-product cross-product ;
 
[let
{ 3 4 5 } :> a
{ 4 3 5 } :> b
{ -5 -12 -13 } :> c
"a: " write a .
"b: " write b .
"c: " write c . nl
"a . b: " write a b dot-product .
"a x b: " write a b cross-product .
"a . (b x c): " write a b c scalar-triple-product .
"a x (b x c): " write a b c vector-triple-product .
]</syntaxhighlight>
{{out}}
<pre>
a: { 3 4 5 }
b: { 4 3 5 }
c: { -5 -12 -13 }
 
a . b: 49
a x b: { 5 5 -7 }
a . (b x c): 6
a x (b x c): { -267 204 -3 }
</pre>
 
=={{header|Fantom}}==
<langsyntaxhighlight lang="fantom">class Main
{
Int dot_product (Int[] a, Int[] b)
Line 742 ⟶ 1,780:
echo ("a x (b x c) = [" + vector_triple_product(a, b, c).join (", ") + "]")
}
}</langsyntaxhighlight>
Output:
<pre>
Line 750 ⟶ 1,788:
a x (b x c) = [-267, 204, -3]
</pre>
 
=={{header|Forth}}==
{{works with|Forth|1994 ANSI with a separate floating point stack.}}<syntaxhighlight lang="forth">
: 3f! ( &v - ) ( f: x y z - ) dup float+ dup float+ f! f! f! ;
 
: Vector \ Compiletime: ( f: x y z - ) ( <name> - )
create here [ 3 floats ] literal allot 3f! ; \ Runtime: ( - &v )
 
: >fx@ ( &v - ) ( f: - n ) postpone f@ ; immediate
: >fy@ ( &v - ) ( f: - n ) float+ f@ ;
: >fz@ ( &v - ) ( f: - n ) float+ float+ f@ ;
: .Vector ( &v - ) dup >fz@ dup >fy@ >fx@ f. f. f. ;
 
: Dot* ( &v1 &v2 - ) ( f - DotPrd )
2dup >fx@ >fx@ f*
2dup >fy@ >fy@ f* f+
>fz@ >fz@ f* f+ ;
 
: Cross* ( &v1 &v2 &vResult - )
>r 2dup >fz@ >fy@ f*
2dup >fy@ >fz@ f* f-
2dup >fx@ >fz@ f*
2dup >fz@ >fx@ f* f-
2dup >fy@ >fx@ f*
>fx@ >fy@ f* f-
r> 3f! ;
 
: ScalarTriple* ( &v1 &v2 &v3 - ) ( f: - ScalarTriple* )
>r pad Cross* pad r> Dot* ;
 
: VectorTriple* ( &v1 &v2 &v3 &vDest - )
>r swap r@ Cross* r> tuck Cross* ;
 
3e 4e 5e Vector A
4e 3e 5e Vector B
-5e -12e -13e Vector C
 
cr
cr .( a . b = ) A B Dot* f.
cr .( a x b = ) A B pad Cross* pad .Vector
cr .( a . [b x c] = ) A B C ScalarTriple* f.
cr .( a x [b x c] = ) A B C pad VectorTriple* pad .Vector </syntaxhighlight>
{{out}}
<pre>
a . b = 49.0000
a x b = 5.00000 5.00000 -7.00000
a . [b x c] = 6.00000
a x [b x c] = -267.000 204.000 -3.00000
</pre>
{{libheader|Forth Scientific Library}}<syntaxhighlight lang="forth">
S" fsl-util.fs" REQUIRED
: 3f! 3 SWAP }fput ;
: vector
CREATE
HERE 3 DUP FLOAT DUP , * ALLOT SWAP CELL+ }fput
DOES>
CELL+ ;
: >fx@ 0 } F@ ;
: >fy@ 1 } F@ ;
: >fz@ 2 } F@ ;
: .Vector 3 SWAP }fprint ;
0e 0e 0e vector pad \ NB: your system will be non-standard after this line
\ From here on is identical to the above example</syntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
Specialized for 3-dimensional vectors.
<langsyntaxhighlight lang="fortran">program VectorProducts
 
real, dimension(3) :: a, b, c
Line 792 ⟶ 1,893:
end function v3_product
 
end program VectorProducts</langsyntaxhighlight>
Output
<pre> 49.0000
5.00000 5.00000 -7.00000
6.00000
-267.000 204.000 -3.00000</pre>
</pre>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic"> 'Construct only required operators for this.
Type V3
As double x,y,z
declare operator cast() as string
End Type
#define dot *
#define cross ^
#define Show(t1,t) ? #t1;tab(22);t
 
operator V3.cast() as string
return "("+str(x)+","+str(y)+","+str(z)+")"
end operator
 
Operator dot(v1 As v3,v2 As v3) As double
Return v1.x*v2.x+v1.y*v2.y+v1.z*v2.z
End Operator
 
Operator cross(v1 As v3,v2 As v3) As v3
Return type<v3>(v1.y*v2.z-v2.y*v1.z,-(v1.x*v2.z-v2.x*v1.z),v1.x*v2.y-v2.x*v1.y)
End Operator
 
dim as V3 a = (3, 4, 5), b = (4, 3, 5), c = (-5, -12, -13)
 
Show(a,a)
Show(b,b)
Show(c,c)
?
Show(a . b,a dot b)
Show(a X b,a cross b)
Show(a . b X c,a dot b cross c)
Show(a X (b X c),a cross (b cross c))
sleep</syntaxhighlight>
{{out}}
<pre>a (3,4,5)
b (4,3,5)
c (-5,-12,-13)
 
a . b 49
a X b (5,5,-7)
a . b X c 6
a X (b X c) (-267,204,-3)</pre>
 
=={{header|FunL}}==
<syntaxhighlight lang="funl">A = (3, 4, 5)
B = (4, 3, 5)
C = (-5, -12, -13)
 
def dot( u, v ) = sum( u(i)v(i) | i <- 0:u.>length() )
def cross( u, v ) = (u(1)v(2) - u(2)v(1), u(2)v(0) - u(0)v(2), u(0)v(1) - u(1)v(0) )
def scalarTriple( u, v, w ) = dot( u, cross(v, w) )
def vectorTriple( u, v, w ) = cross( u, cross(v, w) )
 
println( "A\u00b7B = ${dot(A, B)}" )
println( "A\u00d7B = ${cross(A, B)}" )
println( "A\u00b7(B\u00d7C) = ${scalarTriple(A, B, C)}" )
println( "A\u00d7(B\u00d7C) = ${vectorTriple(A, B, C)}" )</syntaxhighlight>
 
{{out}}
 
<pre>
A·B = 49
A×B = (5, 5, -7)
A·(B×C) = 6
A×(B×C) = (-267, 204, -3)
</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">DotProduct := function(u, v)
return u*v;
end;
Line 837 ⟶ 2,006:
 
VectorTripleProduct(a, b, c);
# [ -267, 204, -3 ]</langsyntaxhighlight>
 
=={{header|GLSL}}==
{{trans|C}}
<syntaxhighlight lang="glsl">
vec3 a = vec3(3, 4, 5),b = vec3(4, 3, 5),c = vec3(-5, -12, -13);
float dotProduct(vec3 a, vec3 b)
{
return a.x*b.x+a.y*b.y+a.z*b.z;
}
vec3 crossProduct(vec3 a,vec3 b)
{
vec3 c = vec3(a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y- a.y*b.x);
return c;
}
float scalarTripleProduct(vec3 a,vec3 b,vec3 c)
{
return dotProduct(a,crossProduct(b,c));
}
vec3 vectorTripleProduct(vec3 a,vec3 b,vec3 c)
{
return crossProduct(a,crossProduct(b,c));
}
</syntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 875 ⟶ 2,072:
fmt.Println(s3(a, b, c))
fmt.Println(v3(a, b, c))
}</langsyntaxhighlight>
Output:
<pre>
Line 886 ⟶ 2,083:
=={{header|Groovy}}==
Dot Product Solution:
<langsyntaxhighlight lang="groovy">def pairwiseOperation = { x, y, Closure binaryOp ->
assert x && y && x.size() == y.size()
[x, y].transpose().collect(binaryOp)
Line 896 ⟶ 2,093:
assert x && y && x.size() == y.size()
pwMult(x, y).sum()
}</langsyntaxhighlight>
Cross Product Solution, using scalar operations:
<langsyntaxhighlight lang="groovy">def crossProductS = { x, y ->
assert x && y && x.size() == 3 && y.size() == 3
[x[1]*y[2] - x[2]*y[1], x[2]*y[0] - x[0]*y[2] , x[0]*y[1] - x[1]*y[0]]
}</langsyntaxhighlight>
Cross Product Solution, using "vector" operations:
<langsyntaxhighlight lang="groovy">def rotR = {
assert it && it.size() > 2
[it[-1]] + it[0..-2]
Line 918 ⟶ 2,115:
assert x && y && x.size() == 3 && y.size() == 3
pwSubtr(pwMult(rotL(x), rotR(y)), pwMult(rotL(y), rotR(x)))
}</langsyntaxhighlight>
Test program (including triple products):
<langsyntaxhighlight lang="groovy">def test = { crossProduct ->
 
def scalarTripleProduct = { x, y, z ->
Line 942 ⟶ 2,139:
 
test(crossProductS)
test(crossProductV)</langsyntaxhighlight>
Output:
<pre> a . b = 49
Line 955 ⟶ 2,152:
 
=={{header|Haskell}}==
<syntaxhighlight lang ="haskell">typeimport VectorData.Monoid a = [a]((<>))
 
type Vector a = [a]
 
type Scalar a = a
 
a, b, c, d :: Vector Int
a = [ 3, 4, 5 ]
b = [ 4, 3, 5 ]
c = [-5,-12,-13 ]
d = [ 3, 4, 5, 6 ]
 
b = [4, 3, 5]
dot :: (Num t) => Vector t -> Vector t -> Scalar t
dot u v | length u == length v = sum $ zipWith (*) u v
| otherwise = error "Dotted Vectors must be of equal dimension."
 
c = [-5, -12, -13]
cross :: (Num t) => Vector t -> Vector t -> Vector t
cross u v | length u == 3 && length v == 3 =
[u !! 1 * v !! 2 - u !! 2 * v !! 1,
u !! 2 * v !! 0 - u !! 0 * v !! 2,
u !! 0 * v !! 1 - u !! 1 * v !! 0]
| otherwise = error "Crossed Vectors must both be three dimensional."
 
d = [3, 4, 5, 6]
scalarTriple :: (Num t) => Vector t -> Vector t -> Vector t -> Scalar t
 
dot
:: (Num t)
=> Vector t -> Vector t -> Scalar t
dot u v
| length u == length v = sum $ zipWith (*) u v
| otherwise = error "Dotted Vectors must be of equal dimension."
 
cross
:: (Num t)
=> Vector t -> Vector t -> Vector t
cross u v
| length u == 3 && length v == 3 =
[ u !! 1 * v !! 2 - u !! 2 * v !! 1
, u !! 2 * head v - head u * v !! 2
, head u * v !! 1 - u !! 1 * head v
]
| otherwise = error "Crossed Vectors must both be three dimensional."
 
scalarTriple
:: (Num t)
=> Vector t -> Vector t -> Vector t -> Scalar t
scalarTriple q r s = dot q $ cross r s
 
vectorTriple
vectorTriple :: (Num t) => Vector t -> Vector t -> Vector t -> Vector t
:: (Num t)
=> Vector t -> Vector t -> Vector t -> Vector t
vectorTriple q r s = cross q $ cross r s
 
main =:: doIO ()
main =
mapM_ putStrLn [ "a . b = " ++ (show $ dot a b)
mapM_
, "a x b = " ++ (show $ cross a b)
putStrLn
, "a . b x c = " ++ (show $ scalarTriple a b c)
,[ "a x. b x c = " ++<> (show $ vectorTriple(dot a b c)
, "a .x db = " ++<> (show $ dot(cross a db) ]</lang>
, "a . b x c = " <> show (scalarTriple a b c)
Output:<pre>
, "a .x b x c = " =<> show (vectorTriple a b 49c)
, "a . d = " <> show (dot a d)
]</syntaxhighlight>
Output:<pre>a . b = 49
a x b = [5,5,-7]
a . b x c = 6
a x b x c = [-267,204,-3]
a . d = *** Exception: Dotted Vectors must be of equal dimension.</pre>
a . d = </pre>
 
 
Or using '''Either''' and '''(>>=)''', rather than '''error''', to pass on intelligible messages:
 
<syntaxhighlight lang="haskell">dotProduct
:: Num a
=> [a] -> [a] -> Either String a
dotProduct xs ys
| length xs /= length ys =
Left "Dot product not defined - vectors differ in dimension."
| otherwise = Right (sum $ zipWith (*) xs ys)
 
crossProduct
:: Num a
=> [a] -> [a] -> Either String [a]
crossProduct xs ys
| 3 /= length xs || 3 /= length ys =
Left "crossProduct is defined only for 3d vectors."
| otherwise = Right [x2 * y3 - x3 * y2, x3 * y1 - x1 * y3, x1 * y2 - x2 * y1]
where
[x1, x2, x3] = xs
[y1, y2, y3] = ys
 
scalarTriple
:: Num a
=> [a] -> [a] -> [a] -> Either String a
scalarTriple q r s = crossProduct r s >>= dotProduct q
 
vectorTriple
:: Num a
=> [a] -> [a] -> [a] -> Either String [a]
vectorTriple q r s = crossProduct r s >>= crossProduct q
 
-- TEST ---------------------------------------------------
a = [3, 4, 5]
 
b = [4, 3, 5]
 
c = [-5, -12, -13]
 
d = [3, 4, 5, 6]
 
main :: IO ()
main =
mapM_ putStrLn $
zipWith
(++)
["a . b", "a x b", "a . b x c", "a x b x c", "a . d", "a . (b x d)"]
[ sh $ dotProduct a b
, sh $ crossProduct a b
, sh $ scalarTriple a b c
, sh $ vectorTriple a b c
, sh $ dotProduct a d
, sh $ scalarTriple a b d
]
 
sh
:: Show a
=> Either String a -> String
sh = either (" => " ++) ((" = " ++) . show)</syntaxhighlight>
{{Out}}
<pre>a . b = 49
a x b = [5,5,-7]
a . b x c = 6
a x b x c = [-267,204,-3]
a . d => Dot product not defined - vectors differ in dimension.
a . (b x d) => crossProduct is defined only for 3d vectors.</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang="icon"># record type to store a 3D vector
record Vector3D(x, y, z)
 
Line 1,036 ⟶ 2,321:
writes ("Ax(BxC) : " || toString(a) || "x(" || toString(b) || "x" || toString(c) || ") = ")
write (toString(vectorTriple (a, b, c)))
end</langsyntaxhighlight>
Output:
<pre>
Line 1,046 ⟶ 2,331:
 
=={{header|J}}==
Perhaps the most straightforward definition for cross product in J uses rotate multiply and subtract:
Based on [[j:Essays/Complete Tensor]]:
 
<lang j>CT=: C.!.2 @ (#:i.) @ $~
<syntaxhighlight lang="j">cross=: (1&|.@[ * 2&|.@]) - 2&|.@[ * 1&|.@]</syntaxhighlight>
or
<syntaxhighlight lang="j">cross=: {{ ((1|.x)*2|.y) - (2|.x)*1|.y }}</syntaxhighlight>
 
 
However, there are other valid approaches. For example, a "generalized approach" based on [[j:Essays/Complete Tensor]]:
<syntaxhighlight lang="j">CT=: C.!.2 @ (#:i.) @ $~
ip=: +/ .* NB. inner product
cross=: ] ip CT@#@[ ip [</langsyntaxhighlight>
 
Note that there are a variety of other generalizations have cross products as a part of what they do. (For example, we could implement cross product using complex numbers in a Cayley Dickson implementation of quaternion product.)
 
An alternative definition for cross (based on finding the determinant of a 3 by 3 matrix where one row is unit vectors) could be:
<langsyntaxhighlight lang="j">cross=: [: > [: -&.>/ .(*&.>) (<"1=i.3) , ,:&:(<"0)</langsyntaxhighlight>
or
Implementation:
<syntaxhighlight lang="j">cross=: {{ >-L:0/ .(*L:0) (<"1=i.3), x,:&:(<"0) y}}</syntaxhighlight>
<lang j>a=: 3 4 5
 
With an implementation of cross product and inner product, the rest of the task becomes trivial:
 
<syntaxhighlight lang="j">a=: 3 4 5
b=: 4 3 5
c=: -5 12 13
Line 1,064 ⟶ 2,363:
crossP=: A cross B
scTriP=: A ip B cross C
veTriP=: A cross B cross C</langsyntaxhighlight>
Required example:
<langsyntaxhighlight lang="j"> dotP a;b
49
crossP a;b
Line 1,073 ⟶ 2,372:
6
veTriP a;b;c
_267 204 _3</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
All operations which return vectors give vectors containing <code>Double</code>s.
<langsyntaxhighlight lang="java5">public class VectorProds{
public static class Vector3D<T extends Number>{
private T a, b, c;
Line 1,125 ⟶ 2,424:
System.out.println(a.vecTrip(b, c));
}
}</langsyntaxhighlight>
Output:
<pre>49.0
Line 1,131 ⟶ 2,430:
6.0
<-267.0, 204.0, -3.0></pre>
{{works with|Java|1.8+}}
This solution uses Java SE new Stream API
<syntaxhighlight lang="java8">import java.util.Arrays;
import java.util.stream.IntStream;
 
public class VectorsOp {
// Vector dot product using Java SE 8 stream abilities
// the method first create an array of size values,
// and map the product of each vectors components in a new array (method map())
// and transform the array to a scalr by summing all elements (method reduce)
// the method parallel is there for optimization
private static int dotProduct(int[] v1, int[] v2,int length) {
int result = IntStream.range(0, length)
.parallel()
.map( id -> v1[id] * v2[id])
.reduce(0, Integer::sum);
 
return result;
}
 
// Vector Cross product using Java SE 8 stream abilities
// here we map in a new array where each element is equal to the cross product
// With Stream is is easier to handle N dimensions vectors
private static int[] crossProduct(int[] v1, int[] v2,int length) {
 
int result[] = new int[length] ;
//result[0] = v1[1] * v2[2] - v1[2]*v2[1] ;
//result[1] = v1[2] * v2[0] - v1[0]*v2[2] ;
// result[2] = v1[0] * v2[1] - v1[1]*v2[0] ;
result = IntStream.range(0, length)
.parallel()
.map( i -> v1[(i+1)%length] * v2[(i+2)%length] - v1[(i+2)%length]*v2[(i+1)%length])
.toArray();
 
return result;
}
 
public static void main (String[] args)
{
int[] vect1 = {3, 4, 5};
int[] vect2 = {4, 3, 5};
int[] vect3 = {-5, -12, -13};
 
System.out.println("dot product =:" + dotProduct(vect1,vect2,3));
 
int[] prodvect = new int[3];
prodvect = crossProduct(vect1,vect2,3);
System.out.println("cross product =:[" + prodvect[0] + ","
+ prodvect[1] + ","
+ prodvect[2] + "]");
 
prodvect = crossProduct(vect2,vect3,3);
System.out.println("scalar product =:" + dotProduct(vect1,prodvect,3));
 
prodvect = crossProduct(vect1,prodvect,3);
 
System.out.println("triple product =:[" + prodvect[0] + ","
+ prodvect[1] + ","
+ prodvect[2] + "]");
 
}
}</syntaxhighlight>
result is the same as above , fortunately
<pre>dot product =:49
cross product =:[5,5,-7]
scalar product =:6
triple product =:[-267,204,-3]</pre>
 
=={{header|JavaScript}}==
===ES5===
The <code>dotProduct()</code> function is generic and will create a dot product of any set of vectors provided they are all the same dimension.
The <code>crossProduct()</code> function expects two 3D vectors.
<langsyntaxhighlight lang="javascript">function dotProduct() {
var len = arguments[0] && arguments[0].length;
var argsLen = arguments.length;
Line 1,204 ⟶ 2,573:
'A x (B x C): ' + vectorTripleProduct(a, b, c)
);
}());</langsyntaxhighlight>
{{Out}}
Output:
<pre>A . B: 49
A . B: 49
A x B: 5,5,-7
A . (B x C): 6
A x (B x C): -267,204,-3</pre>
 
===ES6===
<syntaxhighlight lang="javascript">(() => {
'use strict';
 
// dotProduct :: [a] -> [a] -> Either String a
const dotProduct = xs =>
// Dot product of two vectors of equal dimension.
ys => xs.length !== ys.length ? (
Left('Dot product not defined - vectors differ in dimension.')
) : Right(sum(
zipWith(mul)(Array.from(xs))(Array.from(ys))
));
 
// crossProduct :: Num a => (a, a, a) -> (a, a, a)
// Either String -> (a, a, a)
const crossProduct = xs =>
// Cross product of two 3D vectors.
ys => 3 !== xs.length || 3 !== ys.length ? (
Left('crossProduct is defined only for 3d vectors.')
) : Right((() => {
const [x1, x2, x3] = Array.from(xs);
const [y1, y2, y3] = Array.from(ys);
return [
x2 * y3 - x3 * y2,
x3 * y1 - x1 * y3,
x1 * y2 - x2 * y1
];
})());
 
// scalarTriple :: Num a => (a, a, a) -> (a, a, a) -> (a, a a) ->
// Either String -> a
const scalarTriple = q =>
// The scalar triple product.
r => s => bindLR(crossProduct(r)(s))(
dotProduct(q)
);
 
// vectorTriple :: Num a => (a, a, a) -> (a, a, a) -> (a, a a) ->
// Either String -> (a, a, a)
const vectorTriple = q =>
// The vector triple product.
r => s => bindLR(crossProduct(r)(s))(
crossProduct(q)
);
 
// main :: IO ()
const main = () => {
// TEST -------------------------------------------
const
a = [3, 4, 5],
b = [4, 3, 5],
c = [-5, -12, -13],
d = [3, 4, 5, 6];
 
console.log(unlines(
zipWith(k => f => k + show(
saturated(f)([a, b, c])
))(['a . b', 'a x b', 'a . (b x c)', 'a x (b x c)'])(
[dotProduct, crossProduct, scalarTriple, vectorTriple]
)
.concat([
'a . d' + show(
dotProduct(a)(d)
),
'a . (b x d)' + show(
scalarTriple(a)(b)(d)
)
])
));
};
 
 
// GENERIC FUNCTIONS ----------------------------------
 
// Left :: a -> Either a b
const Left = x => ({
type: 'Either',
Left: x
});
 
// Right :: b -> Either a b
const Right = x => ({
type: 'Either',
Right: x
});
 
// bindLR (>>=) :: Either a -> (a -> Either b) -> Either b
const bindLR = m => mf =>
undefined !== m.Left ? (
m
) : mf(m.Right);
 
// either :: (a -> c) -> (b -> c) -> Either a b -> c
const either = fl => fr => e =>
'Either' === e.type ? (
undefined !== e.Left ? (
fl(e.Left)
) : fr(e.Right)
) : undefined;
 
// identity :: a -> a
const identity = x => x;
 
// mul (*) :: Num a => a -> a -> a
const mul = a => b => a * b;
 
// Curried function -> [Argument] -> a more saturated value
const saturated = f =>
// A curried function applied successively to
// a list of arguments up to, but not beyond,
// the point of saturation.
args => 0 < args.length ? (
args.slice(1).reduce(
(a, x) => 'function' !== typeof a ? (
a
) : a(x),
f(args[0])
)
) : f;
 
// show :: Either String a -> String
const show = x =>
either(x => ' => ' + x)(
x => ' = ' + JSON.stringify(x)
)(x);
 
// sum :: [Num] -> Num
const sum = xs => xs.reduce((a, x) => a + x, 0);
 
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
 
// zipWith:: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = f => xs => ys =>
xs.slice(
0, Math.min(xs.length, ys.length)
).map((x, i) => f(x)(ys[i]));
 
// MAIN ---
return main();
})();</syntaxhighlight>
{{Out}}
<pre>a . b = 49
a x b = [5,5,-7]
a . (b x c) = 6
a x (b x c) = [-267,204,-3]
a . d => Dot product not defined - vectors differ in dimension.
a . (b x d) => crossProduct is defined only for 3d vectors.</pre>
 
=={{header|jq}}==
The <code>dot_product()</code> function is generic and will create a dot product of any pair of vectors provided they are both the same dimension. The other functions expect 3D vectors.<syntaxhighlight lang="jq">def dot_product(a; b):
reduce range(0;a|length) as $i (0; . + (a[$i] * b[$i]) );
 
# for 3d vectors
def cross_product(a;b):
[ a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1]-a[1]*b[0] ];
 
def scalar_triple_product(a;b;c):
dot_product(a; cross_product(b; c));
 
def vector_triple_product(a;b;c):
cross_product(a; cross_product(b; c));
def main:
[3, 4, 5] as $a
| [4, 3, 5] as $b
| [-5, -12, -13] as $c
| "a . b = \(dot_product($a; $b))",
"a x b = [\( cross_product($a; $b) | map(tostring) | join (", ") )]" ,
"a . (b x c) = \( scalar_triple_product ($a; $b; $c)) )",
"a x (b x c) = [\( vector_triple_product($a; $b; $c)|map(tostring)|join (", ") )]" ;</syntaxhighlight>
Output:
<syntaxhighlight lang="jq">"a . b = 49"
"a x b = [5, 5, -7]"
"a . (b x c) = 6 )"
"a x (b x c) = [-267, 204, -3]"</syntaxhighlight>
 
=={{header|Julia}}==
Julia provides dot and cross products with LinearAlgebra. It's easy enough to use these to construct the triple products.
<syntaxhighlight lang="julia">using LinearAlgebra
 
const a = [3, 4, 5]
const b = [4, 3, 5]
const c = [-5, -12, -13]
 
println("Test Vectors:")
@show a b c
 
println("\nVector Products:")
@show a ⋅ b
@show a × b
@show a ⋅ (b × c)
@show a × (b × c)</syntaxhighlight>
 
{{out}}
<pre>
Test Vectors:
a = [3, 4, 5]
b = [4, 3, 5]
c = [-5, -12, -13]
 
Vector Products:
a ⋅ b = 49
a × b = [5, 5, -7]
a ⋅ (b × c) = 6
a × (b × c) = [-267, 204, -3]
</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.2
 
class Vector3D(val x: Double, val y: Double, val z: Double) {
infix fun dot(v: Vector3D) = x * v.x + y * v.y + z * v.z
 
infix fun cross(v: Vector3D) =
Vector3D(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x)
 
fun scalarTriple(v: Vector3D, w: Vector3D) = this dot (v cross w)
 
fun vectorTriple(v: Vector3D, w: Vector3D) = this cross (v cross w)
 
override fun toString() = "($x, $y, $z)"
}
 
fun main(args: Array<String>) {
val a = Vector3D(3.0, 4.0, 5.0)
val b = Vector3D(4.0, 3.0, 5.0)
val c = Vector3D(-5.0, -12.0, -13.0)
println("a = $a")
println("b = $b")
println("c = $c")
println()
println("a . b = ${a dot b}")
println("a x b = ${a cross b}")
println("a . b x c = ${a.scalarTriple(b, c)}")
println("a x b x c = ${a.vectorTriple(b, c)}")
}</syntaxhighlight>
 
{{out}}
<pre>
a = (3.0, 4.0, 5.0)
b = (4.0, 3.0, 5.0)
c = (-5.0, -12.0, -13.0)
 
a . b = 49.0
a x b = (5.0, 5.0, -7.0)
a . b x c = 6.0
a x b x c = (-267.0, 204.0, -3.0)
</pre>
 
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
 
# Vector products
# # dot product (a scalar quantity) A • B = a1b1 + a2b2 + a3b3 + ...
# # cross product (a vector quantity) A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
# # scalar triple product (a scalar quantity) A • (B x C)
# # vector triple product (a vector quantity) A x (B x C)
 
# # Variables:
#
typeset -a A=( 3 4 5 )
typeset -a B=( 4 3 5 )
typeset -a C=( -5 -12 -13 )
 
# # Functions:
#
 
# # Function _dotprod(vec1, vec2) - Return the (scalar) dot product of 2 vectors
#
function _dotprod {
typeset _vec1 ; nameref _vec1="$1" # Input vector 1
typeset _vec2 ; nameref _vec2="$2" # Input vector 2
typeset _i ; typeset -si _i
typeset _dotp ; integer _dotp=0
 
for ((_i=0; _i<${#_vec1[*]}; _i++)); do
(( _dotp+=(_vec1[_i] * _vec2[_i]) ))
done
echo ${_dotp}
}
 
# # Function _crossprod(vec1, vec2, vec) - Return the (vector) cross product of 2 vectors
#
function _crossprod {
typeset _vec1 ; nameref _vec1="$1" # Input vector 1
typeset _vec2 ; nameref _vec2="$2" # Input vector 2
typeset _vec3 ; nameref _vec3="$3" # Output vector
 
_vec3+=( $(( _vec1[1]*_vec2[2] - _vec1[2]*_vec2[1] )) )
_vec3+=( $(( _vec1[2]*_vec2[0] - _vec1[0]*_vec2[2] )) )
_vec3+=( $(( _vec1[0]*_vec2[1] - _vec1[1]*_vec2[0] )) )
}
 
# # Function _scal3prod(vec1, vec2, vec3) - Return the (scalar) scalar triple product of 3 vectors
#
function _scal3prod {
typeset _vec1 ; nameref _vec1="$1" # Input vector 1
typeset _vec2 ; nameref _vec2="$2" # Input vector 2
typeset _vec3 ; nameref _vec3="$3" # Input vector 3
typeset _vect ; typeset -a _vect # temp vector
 
_crossprod _vec2 _vec3 _vect # (B x C)
echo $(_dotprod _vec1 _vect) # A • (B x C)
 
}
 
# # Function _vect3prod(vec1, vec2, vec3, vec) - Return the (vector) vector triple product of 3 vectors
#
function _vect3prod {
typeset _vec1 ; nameref _vec1="$1" # Input vector 1
typeset _vec2 ; nameref _vec2="$2" # Input vector 2
typeset _vec3 ; nameref _vec3="$3" # Input vector 3
typeset _vec4 ; nameref _vec4="$4" # Output vector
typeset _vect ; typeset -a _vect # temp vector
 
_crossprod _vec2 _vec3 _vect # (B x C)
_crossprod _vec1 _vect _vec4 # A x (B x C)
}
 
######
# main #
######
 
print "The dot product A • B = $(_dotprod A B)"
 
typeset -a arr
_crossprod A B arr
print "The cross product A x B = ( ${arr[@]} )"
 
print "The scalar triple product A • (B x C) = $(_scal3prod A B C)"
 
typeset -m crossprod=arr ; typeset -a arr
_vect3prod A B C arr
print "The vector triple product A x (B x C) = ( ${arr[@]} )"
</syntaxhighlight>
{{out}}<pre>
The dot product A • B = 49
The cross product A x B = ( 5 5 -7 )
The scalar triple product A • (B x C) = 6
The vector triple product A x (B x C) = ( -267 204 -3 )</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def dotProduct
{lambda {:a :b}
{+ {* {A.get 0 :a} {A.get 0 :b}}
{* {A.get 1 :a} {A.get 1 :b}}
{* {A.get 2 :a} {A.get 2 :b}}}}}
-> dotProduct
 
{def crossProduct
{lambda {:a :b}
{A.new {- {* {A.get 1 :a} {A.get 2 :b}}
{* {A.get 2 :a} {A.get 1 :b}}}
{- {* {A.get 2 :a} {A.get 0 :b}}
{* {A.get 0 :a} {A.get 2 :b}}}
{- {* {A.get 0 :a} {A.get 1 :b}}
{* {A.get 1 :a} {A.get 0 :b}}} }}}
-> crossProduct
 
{def A {A.new 3 4 5}} -> A = [3,4,5]
{def B {A.new 4 3 5}} -> B = [4,3,5]
{def C {A.new -5 -12 -13}} -> C = [4,3,5]
 
A.B : {dotProduct {A} {B}} -> 49
AxB : {crossProduct {A} {B}} -> [5,5,-7]
A.(BxC) : {dotProduct {A} {crossProduct {B} {C}}} -> 6
Ax(BxC) : {crossProduct {A} {crossProduct {B} {C}}} -> [-267,204,-3]
</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb"> print "Vector products of 3-D vectors"
 
print "Dot product of 3,4,5 and 4,3,5 is "
Line 1,258 ⟶ 2,997:
VectorTripleProduct$ =CrossProduct$( i$, CrossProduct$( j$, k$))
end function
END SUB</langsyntaxhighlight>
 
=={{header|Lingo}}==
Lingo has a built-in vector data type that supports calculation of both dot and cross products:
<syntaxhighlight lang="lingo">a = vector(1,2,3)
b = vector(4,5,6)
 
put a * b
-- 32.0000
 
put a.dot(b)
-- 32.0000
 
put a.cross(b)
-- vector( -3.0000, 6.0000, -3.0000 )</syntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">Vector = {}
function Vector.new( _x, _y, _z )
return { x=_x, y=_y, z=_z }
Line 1,297 ⟶ 3,050:
 
r = Vector.vector_triple( A, B, C )
print( r.x, r.y, r.z )</langsyntaxhighlight>
<pre>49
5 5 -7
Line 1,303 ⟶ 3,056:
-267 204 -3</pre>
 
=={{header|MathematicaM2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang Mathematica>a={3,4,5};
Module checkit {
class Vector {
\\ by default are double
a,b,c
Property ToString$ {
Value {
link parent a,b,c to a,b,c
value$=format$("({0}, {1}, {2})",a,b,c)
}
}
Operator "==" {
read n
push .a==n.a and .b==n.b and .c==n.c
}
Operator Unary {
.a-! : .b-! : .c-!
}
Operator "+" {
Read v2
For this, v2 {
.a+=..a :.b+=..b:.c+=..c:
}
}
Function Mul(r) {
vv=this
for vv {
.a*=r:.b*=r:.c*=r
}
=vv
}
Function Dot(v2) {
def double sum
for this, v2 {
sum=.a*..a+.b*..b+.c*..c
}
=sum
}
Operator "*" {
Read v2
For This, v2 {
Push .b*..c-.c*..b
Push .c*..a-.a*..c
.c<=.a*..b-.b*..a
Read .b, .a
}
}
class:
module Vector {
if match("NNN") then {
Read .a,.b,.c
}
}
}
A=Vector(3,4,5)
B=Vector(4,3,5)
C=Vector(-5,-12,-13)
Print "A=";A.toString$
Print "B=";B.toString$
Print "C=";C.toString$
Print "A dot B="; A.dot(B)
AxB=A*B
Print "A x B="; AxB.toString$
Print "A dot (B x C)=";A.dot(B*C)
AxBxC=A*(B*C)
Print "A x (B x C)=";AxBxC.toString$
Def ToString$(a)=a.toString$
Print "A x (B x C)=";ToString$(A*(B*C))
}
Checkit
</syntaxhighlight>
{{out}}
<pre >
A=(3, 4, 5)
B=(4, 3, 5)
C=(-5, -12, -13)
A dot B=49
A x B=(5, 5, -7)
A dot (B x C)=6
A x (B x C)=(-267, 204, -3)
A x (B x C)=(-267, 204, -3)
</pre >
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">with(LinearAlgebra):
A := Vector([3,4,5]):
B := Vector([4,3,5]):
C := Vector([-5,-12,-13]):
>>>A.B;
49
>>>CrossProduct(A,B);
Vector([5, 5, -7])
>>>A.(CrossProduct(B,C));
6
>>>CrossProduct(A,CrossProduct(B,C));
Vector([-267, 204, -3])</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">a={3,4,5};
b={4,3,5};
c={-5,-12,-13};
Line 1,310 ⟶ 3,161:
Cross[a,b]
a.Cross[b,c]
Cross[a,Cross[b,c]]</langsyntaxhighlight>
{{out}}
Output
<pre>49
{5,5,-7}
Line 1,319 ⟶ 3,170:
=={{header|MATLAB}} / {{header|Octave}}==
Matlab / Octave use double precesion numbers per default, and pi is a builtin constant value. Arbitrary precision is only implemented in some additional toolboxes (e.g. symbolic toolbox).
<langsyntaxhighlight MATLABlang="matlab">% Create a named function/subroutine/method to compute the dot product of two vectors.
dot(a,b)
% Create a function to compute the cross product of two vectors.
Line 1,334 ⟶ 3,185:
dot(a,cross(b,c))
% Compute and display: a x b x c, the vector triple product.
cross(a,cross(b,c))</langsyntaxhighlight>
 
Code for testing:
Line 1,366 ⟶ 3,217:
 
=={{header|Mercury}}==
<syntaxhighlight lang="text">:- module vector_product.
:- interface.
 
Line 1,407 ⟶ 3,258:
 
to_string(vector3d(X, Y, Z)) =
string.format("(%d, %d, %d)", [i(X), i(Y), i(Z)]).</langsyntaxhighlight>
 
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">vectorA = [3, 4, 5]
vectorB = [4, 3, 5]
vectorC = [-5, -12, -13]
 
dotProduct = function(x, y)
return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
end function
 
crossProduct = function(x, y)
return [x[1]*y[2] - x[2]*y[1], x[2]*y[0] - x[0]*y[2], x[0]*y[1] - x[1]*y[0]]
end function
 
print "Dot Product = " + dotProduct(vectorA, vectorB)
print "Cross Product = " + crossProduct(vectorA, vectorB)
print "Scalar Triple Product = " + dotProduct(vectorA, crossProduct(vectorB,vectorC))
print "Vector Triple Product = " + crossProduct(vectorA, crossProduct(vectorB,vectorC))
</syntaxhighlight>
{{out}}
<pre>
Dot Product = 49
Cross Product = [5, 5, -7]
Scalar Triple Product = 6
Vector Triple Product = [-267, 204, -3]
</pre>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">ПП 54 С/П ПП 66 С/П
ИП0 ИП3 ИП6 П3 -> П0 -> П6
ИП1 ИП4 ИП7 П4 -> П1 -> П7
ИП2 ИП5 ИП8 П5 -> П2 -> П8
ПП 66
ИП6 ИП7 ИП8 П2 -> П1 -> П0
ИП9 ИПA ИПB П5 -> П4 -> П3
ПП 54 С/П ПП 66 С/П
ИП0 ИП3 * ИП1 ИП4 * + ИП2 ИП5 * + В/О
ИП1 ИП5 * ИП2 ИП4 * - П9
ИП2 ИП3 * ИП0 ИП5 * - ПA
ИП0 ИП4 * ИП1 ИП3 * - ПB В/О</syntaxhighlight>
 
''Instruction'': Р0 - a<sub>1</sub>, Р1 - a<sub>2</sub>, Р2 - a<sub>3</sub>, Р3 - b<sub>1</sub>, Р4 - b<sub>2</sub>, Р5 - b<sub>3</sub>, Р6 - c<sub>1</sub>, Р7 - c<sub>2</sub>, Р8 - c<sub>3</sub>; В/О С/П.
 
=={{header|Modula-2}}==
<syntaxhighlight lang="modula2">MODULE VectorProducts;
FROM RealStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
 
PROCEDURE WriteReal(r : REAL);
VAR buf : ARRAY[0..31] OF CHAR;
BEGIN
RealToStr(r, buf);
WriteString(buf)
END WriteReal;
 
TYPE Vector = RECORD
a,b,c : REAL;
END;
 
PROCEDURE Dot(u,v : Vector) : REAL;
BEGIN
RETURN u.a * v.a
+ u.b * v.b
+ u.c * v.c
END Dot;
 
PROCEDURE Cross(u,v : Vector) : Vector;
BEGIN
RETURN Vector{
u.b*v.c - u.c*v.b,
u.c*v.a - u.a*v.c,
u.a*v.b - u.b*v.a
}
END Cross;
 
PROCEDURE ScalarTriple(u,v,w : Vector) : REAL;
BEGIN
RETURN Dot(u, Cross(v, w))
END ScalarTriple;
 
PROCEDURE VectorTriple(u,v,w : Vector) : Vector;
BEGIN
RETURN Cross(u, Cross(v, w))
END VectorTriple;
 
PROCEDURE WriteVector(v : Vector);
BEGIN
WriteString("<");
WriteReal(v.a);
WriteString(", ");
WriteReal(v.b);
WriteString(", ");
WriteReal(v.c);
WriteString(">")
END WriteVector;
 
VAR a,b,c : Vector;
BEGIN
a := Vector{3.0, 4.0, 5.0};
b := Vector{4.0, 3.0, 5.0};
c := Vector{-5.0, -12.0, -13.0};
 
WriteVector(a);
WriteString(" dot ");
WriteVector(b);
WriteString(" = ");
WriteReal(Dot(a,b));
WriteLn;
 
WriteVector(a);
WriteString(" cross ");
WriteVector(b);
WriteString(" = ");
WriteVector(Cross(a,b));
WriteLn;
 
WriteVector(a);
WriteString(" cross (");
WriteVector(b);
WriteString(" cross ");
WriteVector(c);
WriteString(") = ");
WriteVector(VectorTriple(a,b,c));
WriteLn;
 
ReadChar
END VectorProducts.</syntaxhighlight>
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System.Console;
 
module VectorProducts3d
Line 1,445 ⟶ 3,423:
WriteLine(VectorTriple(a, b, c));
}
}</langsyntaxhighlight>
Outputs
<pre>49
Line 1,451 ⟶ 3,429:
6
(-267, 204, -3)</pre>
 
=={{header|Never}}==
<syntaxhighlight lang="fsharp">func printv(a[d] : float) -> int {
prints("[" + a[0] + ", " + a[1] + ", " + a[2] + "]\n");
0
}
 
func dot(a[d1] : float, b[d2] : float) -> float {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
 
func cross(a[d1] : float, b[d2] : float) -> [_] : float {
[ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ] : float
}
 
func scalar_triple(a[d1] : float, b[d2] : float, c[d3] : float) -> float {
dot(a, cross(b, c))
}
 
func vector_triple(a[d1] : float, b[d2] : float, c[d3] : float) -> [_] : float {
cross(a, cross(b, c))
}
 
func main() -> int {
var a = [ 3.0, 4.0, 5.0 ] : float;
var b = [ 4.0, 3.0, 5.0 ] : float;
var c = [ -5.0, -12.0, -13.0 ] : float;
 
printv(a);
printv(b);
printv(c);
printf(dot(a, b));
printv(cross(a, b));
printf(scalar_triple(a, b, c));
printv(vector_triple(a, b, c));
0
}
</syntaxhighlight>
Output:
<pre>
[3.00, 4.00, 5.00]
[4.00, 3.00, 5.00]
[-5.00, -12.00, -13.00]
49.00
[5.00, 5.00, -7.00]
6.00
[-267.00, 204.00, -3.00]
</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import strformat, strutils
 
type Vector3 = array[1..3, float]
 
proc `$`(a: Vector3): string =
result = "("
for x in a:
result.addSep(", ", 1)
result.add &"{x}"
result.add ')'
 
proc cross(a, b: Vector3): Vector3 =
result = [a[2]*b[3] - a[3]*b[2], a[3]*b[1] - a[1]*b[3], a[1]*b[2] - a[2]*b[1]]
 
proc dot(a, b: Vector3): float =
for i in a.low..a.high:
result += a[i] * b[i]
 
proc scalarTriple(a, b, c: Vector3): float = a.dot(b.cross(c))
 
proc vectorTriple(a, b, c: Vector3): Vector3 = a.cross(b.cross(c))
 
let
a = [3.0, 4.0, 5.0]
b = [4.0, 3.0, 5.0]
c = [-5.0, -12.0, -13.0]
 
echo &"a ⨯ b = {a.cross(b)}"
echo &"a . b = {a.dot(b)}"
echo &"a . (b ⨯ c) = {scalarTriple(a, b, c)}"
echo &"a ⨯ (b ⨯ c) = {vectorTriple(a, b, c)}"</syntaxhighlight>
 
{{out}}
<pre>a ⨯ b = (5.0, 5.0, -7.0)
a . b = 49.0
a . (b ⨯ c) = 6.0
a ⨯ (b ⨯ c) = (-267.0, 204.0, -3.0)</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">bundle Default {
class VectorProduct {
function : Main(args : String[]) ~ Nil {
Line 1,516 ⟶ 3,581:
}
}
</syntaxhighlight>
</lang>
 
Output:
Line 1,525 ⟶ 3,590:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let a = (3.0, 4.0, 5.0)
let b = (4.0, 3.0, 5.0)
let c = (-5.0, -12.0, -13.0)
Line 1,554 ⟶ 3,619:
Printf.printf "a . (b x c) = %g\n" (scalar_triple a b c);
Printf.printf "a x (b x c) = %s\n" (string_of_vector (vector_triple a b c));
;;</langsyntaxhighlight>
 
outputs:
Line 1,568 ⟶ 3,633:
=={{header|Octave}}==
Octave handles naturally vectors / matrices.
<langsyntaxhighlight lang="octave">a = [3, 4, 5];
b = [4, 3, 5];
c = [-5, -12, -13];
Line 1,592 ⟶ 3,657:
 
% -267 204 -3
v3prod(a, b, c)</langsyntaxhighlight>
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
<lang ooRexx>
a = .vector~new(3, 4, 5);
b = .vector~new(4, 3, 5);
Line 1,645 ⟶ 3,710:
expose x y z
return "<"||x", "y", "z">"
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,655 ⟶ 3,720:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">dot(u,v)={
sum(i=1,#u,u[i]*v[i])
};
Line 1,672 ⟶ 3,737:
cross(a,b)
striple(a,b,c)
vtriple(a,b,c)</langsyntaxhighlight>
Output:
<pre>49
Line 1,680 ⟶ 3,745:
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program VectorProduct (output);
 
type
Line 1,727 ⟶ 3,792:
writeln('a . (b x c): ', scalarTripleProduct(a,b,c):15:8);
write('a x (b x c): '); printVector(vectorTripleProduct(a,b,c));
end.</langsyntaxhighlight>
Output:
<pre>a: 3.00000000 4.00000000 5.00000000
Line 1,737 ⟶ 3,802:
a x (b x c): -267.00000000 204.00000000 -3.00000000
</pre>
 
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
uses System.Numerics;
 
function DotProduct(v1,v2: Vector3): real
:= v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
 
function CrossProduct(v1,v2: Vector3): Vector3
:= new Vector3(v1.y * v2.z - v1.z * v2.y,
v1.z * v2.x - v1.x * v2.z,
v1.x * v2.y - v1.y * v2.x);
 
function ScalarTripleProduct(a,b,c: Vector3): real
:= DotProduct(a, CrossProduct(b, c));
function VectorTripleProduct(a,b,c: Vector3): Vector3
:= CrossProduct(a, CrossProduct(b, c));
 
 
begin
var a := new Vector3(3,4,5);
var b := new Vector3(4,3,5);
var c := new Vector3(-5,-12,-13);
Writeln(DotProduct(a, b));
Writeln(CrossProduct(a, b));
Writeln(ScalarTripleProduct(a, b, c));
Writeln(VectorTripleProduct(a, b, c));
end.
</syntaxhighlight>
{{out}}
<pre>
49
<5. 5. -7>
6
<-267. 204. -3>
</pre>
 
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl">package Vector;
use List::Util 'sum';
use List::MoreUtils 'pairwise';
Line 1,766 ⟶ 3,869:
print "$a x $b = ", $a ^ $b, "\n";
print "$a . ($b x $c) = ", $a & ($b ^ $c), "\n";
print "$a x ($b x $c) = ", $a ^ ($b ^ $c), "\n";</langsyntaxhighlight>
 
Output: <pre>a = (3 4 5) b = (4 3 5) c = (-5 -12 -13)
Line 1,774 ⟶ 3,877:
(3 4 5) x ((4 3 5) x (-5 -12 -13)) = (-267 204 -3)</pre>
 
=={{header|Perl 6Phix}}==
{{libheader|Phix/basics}}
<lang perl6>sub infix:<⋅> { [+] @^a »*« @^b }
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">dot_product</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</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;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">cross_product</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">a1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a3</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">b1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b3</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">b</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">a2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">b3</span><span style="color: #0000FF;">-</span><span style="color: #000000;">a3</span><span style="color: #0000FF;">*</span><span style="color: #000000;">b2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a3</span><span style="color: #0000FF;">*</span><span style="color: #000000;">b1</span><span style="color: #0000FF;">-</span><span style="color: #000000;">a1</span><span style="color: #0000FF;">*</span><span style="color: #000000;">b3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a1</span><span style="color: #0000FF;">*</span><span style="color: #000000;">b2</span><span style="color: #0000FF;">-</span><span style="color: #000000;">a2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">b1</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">scalar_triple_product</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">dot_product</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">cross_product</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">vector_triple_product</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">cross_product</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">cross_product</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">},</span> <span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">4</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;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{-</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">12</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">13</span><span style="color: #0000FF;">}</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" a . b = %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">dot_product</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" a x b = %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">cross_product</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"a . (b x c) = %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">scalar_triple_product</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"a x (b x c) = %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">vector_triple_product</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
a . b = 49
a x b = {5,5,-7}
a . (b x c) = 6
a x (b x c) = {-267,204,-3}
</pre>
 
=={{header|Phixmonti}}==
sub infix:<⨯>([$a1, $a2, $a3], [$b1, $b2, $b3]) {
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt
[ $a2*$b3 - $a3*$b2,
$a3*$b1 - $a1*$b3,
$a1*$b2 - $a2*$b1 ];
}
 
( 3 4 5 ) var vectorA
sub scalar-triple-product { @^a ⋅ (@^b ⨯ @^c) }
( 4 3 5 ) var vectorB
sub vector-triple-product { @^a ⨯ (@^b ⨯ @^c) }
( -5 -12 -13 ) var vectorC
def dotProduct /# x y -- n #/
0 >ps
len for var i
i get rot i get rot * ps> + >ps
endfor
drop drop
ps>
enddef
 
def crossProduct /# x y -- z #/
my @a = <3 4 5>;
1 get rot 2 get rot * >ps
my @b = <4 3 5>;
1 get rot 2 get rot * >ps
my @c = <-5 -12 -13>;
3 get rot 1 get rot * >ps
3 get rot 1 get rot * >ps
2 get rot 3 get rot * >ps
2 get rot 3 get rot * ps> - ps> ps> - ps> ps> - 3 tolist
nip nip
enddef
 
"Dot Product = " print vectorA vectorB dotProduct ?
say (:@a, :@b, :@c).perl;
"Cross Product = " print vectorA vectorB crossProduct ?
say "a ⋅ b = { @a ⋅ @b }";
"Scalar Triple Product = " print vectorB vectorC crossProduct vectorA swap dotProduct ?
say "a ⨯ b = <{ @a ⨯ @b }>";
"Vector Triple Product = " print vectorB vectorC crossProduct vectorA swap crossProduct ?</syntaxhighlight>
say "a ⋅ (b ⨯ c) = { scalar-triple-product(@a, @b, @c) }";
{{out}}
say "a ⨯ (b ⨯ c) = <{ vector-triple-product(@a, @b, @c) }>";</lang>
<pre>Dot Product = 49
Output:
Cross Product = [5, 5, -7]
<pre>("a" => ["3", "4", "5"], "b" => ["4", "3", "5"], "c" => ["-5", "-12", "-13"])
Scalar Triple Product = 6
a ⋅ b = 49
aVector Triple bProduct = <5[-267, 5204, -7>3]
a ⋅ (b ⨯ c) = 6
a ⨯ (b ⨯ c) = <-267 204 -3></pre>
 
=== Press any key to exit ===</pre>
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php"><?php
 
class Vector
Line 1,908 ⟶ 4,055:
new Program();
?>
</syntaxhighlight>
</lang>
 
Output:
Line 1,922 ⟶ 4,069:
A × (B × C) =(-267.00, 204.00, -3.00)
</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
A = [3, 4, 5],
B = [4, 3, 5],
C = [-5, -12, -13],
 
println(a=A),
println(b=B),
println(c=C),
println("A . B"=dot(A,B)),
println("A x B"=cross(A,B)),
println("A . (B x C)"=scalar_triple(A,B,C)),
println("A X (B X C)"=vector_triple(A,B,C)),
nl.
 
dot(A,B) = sum([ AA*BB : {AA,BB} in zip(A,B)]).
cross(A,B) = [A[2]*B[3]-A[3]*B[2], A[3]*B[1]-A[1]*B[3], A[1]*B[2]-A[2]*B[1]].
 
scalar_triple(A,B,C) = dot(A,cross(B,C)).
vector_triple(A,B,C) = cross(A,cross(B,C)).</syntaxhighlight>
 
{{out}}
<pre>a = [3,4,5]
b = [4,3,5]
c = [-5,-12,-13]
A . B = 49
A x B = [5,5,-7]
A . (B x C) = 6
A X (B X C) = [-267,204,-3]</pre>
 
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de dotProduct (A B)
(sum * A B) )
 
Line 1,936 ⟶ 4,115:
 
(de vectorTriple (A B C)
(crossProduct A (crossProduct B C)) )</langsyntaxhighlight>
Test:
<pre>(setq
Line 1,956 ⟶ 4,135:
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">/* dot product, cross product, etc. 4 June 2011 */
 
test_products: procedure options (main);
Line 1,997 ⟶ 4,176:
end vector_triple_product;
 
end test_products;</langsyntaxhighlight>
Results:
<pre>
Line 2,006 ⟶ 4,185:
</pre>
 
<langsyntaxhighlight PLlang="pl/Ii">/* This version uses the ability of PL/I to return arrays. */
 
/* dot product, cross product, etc. 6 June 2011 */
Line 2,053 ⟶ 4,232:
end vector_triple_product;
 
end test_products;</langsyntaxhighlight>
The output is:
<pre>
Line 2,060 ⟶ 4,239:
a . (b x c) = 6
a x (b x c) = -267 204 -3
</pre>
 
=={{header|Plain English}}==
<syntaxhighlight lang="plain english">To run:
Start up.
Make a vector from 3 and 4 and 5.
Make another vector from 4 and 3 and 5.
Make a third vector from -5 and -12 and -13.
Write "A vector: " then the vector on the console.
Write "Another vector: " then the other vector on the console.
Write "A third vector: " then the third vector on the console.
Write "" on the console.
Compute a dot product of the vector and the other vector.
Write "Dot product between the vector and the other vector: " then the dot product on the console.
Compute a cross product of the vector and the other vector.
Write "Cross product between the vector and the other vector: " then the cross product on the console.
Compute a scalar triple product of the vector and the other vector and the third vector.
Write "Scalar triple product between the vector and the other vector and the third vector: " then the scalar triple product on the console.
Compute a vector triple product of the vector and the other vector and the third vector.
Write "Vector triple product between the vector and the other vector and the third vector: " then the vector triple product on the console.
Wait for the escape key.
Shut down.
 
A vector has a first number, a second number, and a third number.
 
To make a vector from a first number and a second number and a third number:
Put the first into the vector's first.
Put the second into the vector's second.
Put the third into the vector's third.
 
To put a vector into another vector:
Put the vector's first into the other vector's first.
Put the vector's second into the other vector's second.
Put the vector's third into the other vector's third.
 
To convert a vector into a string:
Append "(" then the vector's first then ", " then the vector's second then ", " then the vector's third then ")" to the string.
 
A dot product is a number.
 
To compute a dot product of a vector and another vector:
Put the vector's first times the other vector's first into a first number.
Put the vector's second times the other vector's second into a second number.
Put the vector's third times the other vector's third into a third number.
Put the first plus the second plus the third into the dot product.
 
A cross product is a vector.
 
To compute a cross product of a vector and another vector:
Put the vector's second times the other vector's third into a first number.
Put the vector's third times the other vector's second into a second number.
Put the vector's third times the other vector's first into a third number.
Put the vector's first times the other vector's third into a fourth number.
Put the vector's first times the other vector's second into a fifth number.
Put the vector's second times the other vector's first into a sixth number.
Make a result vector from the first minus the second and the third minus the fourth and the fifth minus the sixth.
Put the result into the cross product.
 
A scalar triple product is a number.
 
To compute a scalar triple product of a vector and another vector and a third vector:
Compute a cross product of the other vector and the third vector.
Compute a dot product of the vector and the cross product.
Put the dot product into the scalar triple product.
 
A vector triple product is a vector.
 
To compute a vector triple product of a vector and another vector and a third vector:
Compute a cross product of the other vector and the third vector.
Compute another cross product of the vector and the cross product.
Put the other cross product into the vector triple product.</syntaxhighlight>
{{out}}
<pre>
A vector: (3, 4, 5)
Another vector: (4, 3, 5)
A third vector: (-5, -12, -13)
 
Dot product between the vector and the other vector: 49
Cross product between the vector and the other vector: (5, 5, -7)
Scalar triple product between the vector and the other vector and the third vector: 6
Vector triple product between the vector and the other vector and the third vector: (-267, 204, -3)
</pre>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function dot-product($a,$b) {
$a[0]*$b[0] + $a[1]*$b[1] + $a[2]*$b[2]
}
 
function cross-product($a,$b) {
$v1 = $a[1]*$b[2] - $a[2]*$b[1]
$v2 = $a[2]*$b[0] - $a[0]*$b[2]
$v3 = $a[0]*$b[1] - $a[1]*$b[0]
@($v1,$v2,$v3)
}
 
function scalar-triple-product($a,$b,$c) {
dot-product $a (cross-product $b $c)
}
 
function vector-triple-product($a,$b) {
cross-product $a (cross-product $b $c)
}
 
$a = @(3, 4, 5)
$b = @(4, 3, 5)
$c = @(-5, -12, -13)
 
"a.b = $(dot-product $a $b)"
"axb = $(cross-product $a $b)"
"a.(bxc) = $(scalar-triple-product $a $b $c)"
"ax(bxc) = $(vector-triple-product $a $b $c)"
</syntaxhighlight>
<b>Output:</b>
<pre>
a.b = 49
axb = 5 5 -7
a.(bxc) = 6
ax(bxc) = -267 204 -3
</pre>
 
=={{header|Prolog}}==
Works with SWI-Prolog.
<syntaxhighlight lang="prolog">
dot_product([A1, A2, A3], [B1, B2, B3], Ans) :-
Ans is A1 * B1 + A2 * B2 + A3 * B3.
 
cross_product([A1, A2, A3], [B1, B2, B3], Ans) :-
T1 is A2 * B3 - A3 * B2,
T2 is A3 * B1 - A1 * B3,
T3 is A1 * B2 - A2 * B1,
Ans = [T1, T2, T3].
 
scala_triple(A, B, C, Ans) :-
cross_product(B, C, Temp),
dot_product(A, Temp, Ans).
 
vector_triple(A, B, C, Ans) :-
cross_product(B, C, Temp),
cross_product(A, Temp, Ans).
</syntaxhighlight>
Output:
<pre>
?- dot_product([3.0, 4.0, 5.0], [4.0, 3.0, 5.0], Ans).
Ans = 49.0.
 
?- cross_product([3.0, 4.0, 5.0], [4.0, 3.0, 5.0], Ans).
Ans = [5.0, 5.0, -7.0].
 
?- scala_triple([3.0, 4.0, 5.0], [4.0, 3.0, 5.0], [-5.0, -12.0, -13.0], Ans).
Ans = 6.0.
 
?- vector_triple([3.0, 4.0, 5.0], [4.0, 3.0, 5.0], [-5.0, -12.0, -13.0], Ans).
Ans = [-267.0, 204.0, -3.0].
</pre>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Structure vector
x.f
y.f
Line 2,112 ⟶ 4,445:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>a = [3.00, 4.00, 5.00], b = [4.00, 3.00, 5.00], c = [-5.00, -12.00, -13.00]
Line 2,122 ⟶ 4,455:
=={{header|Python}}==
The solution is in the form of an [[Executable library]].
<langsyntaxhighlight lang="python">def crossp(a, b):
'''Cross product of two 3D vectors'''
assert len(a) == len(b) == 3, 'For 3D vectors only'
Line 2,128 ⟶ 4,461:
b1, b2, b3 = b
return (a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1)
 
def dotp(a,b):
'''Dot product of two eqi-dimensioned vectors'''
assert len(a) == len(b), 'Vector sizes must match'
return sum(aterm * bterm for aterm,bterm in zip(a, b))
 
def scalartriplep(a, b, c):
'''Scalar triple product of three vectors: "a . (b x c)"'''
return dotp(a, crossp(b, c))
 
def vectortriplep(a, b, c):
'''Vector triple product of three vectors: "a x (b x c)"'''
return crossp(a, crossp(b, c))
 
if __name__ == '__main__':
a, b, c = (3, 4, 5), (4, 3, 5), (-5, -12, -13)
print("a = %r; b = %r; c = %r" % (a, b, c))
print("a . b = %r", % dotp(a,b))
print("a x b = %r", % (crossp(a,b),))
print("a . (b x c) = %r", % scalartriplep(a, b, c))
print("a x (b x c) = %r", % (vectortriplep(a, b, c),))</langsyntaxhighlight>
 
;Sample output:
{{out}}
<pre>a = (3, 4, 5); b = (4, 3, 5); c = (-5, -12, -13)
a . b = 49
Line 2,158 ⟶ 4,492:
;Note:
The popular [http://numpy.scipy.org/ numpy] package has functions for dot and cross products.
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ 0 unrot witheach
[ over i^ peek *
rot + swap ]
drop ] is dotproduct ( [ [ --> n )
 
[ join
dup 1 peek over 5 peek *
swap
dup 2 peek over 4 peek *
swap dip -
dup 2 peek over 3 peek *
swap
dup 0 peek over 5 peek *
swap dip -
dup 0 peek over 4 peek *
swap
dup 1 peek swap 3 peek *
- join join ] is crossproduct ( [ [ --> [ )
 
[ crossproduct dotproduct ] is scalartriple ( [ [ [ --> n )
 
[ crossproduct crossproduct ] is vectortriple ( [ [ [ --> [ )
 
[ ' [ 3 4 5 ] ] is a ( --> [ )
[ ' [ 4 3 5 ] ] is b ( --> [ )
[ ' [ -5 -12 -13 ] ] is c ( --> [ )
 
a b dotproduct echo cr
a b crossproduct echo cr
a b c scalartriple echo cr
a b c vectortriple echo cr</syntaxhighlight>
 
{{out}}
 
<pre>49
[ 5 5 -7 ]
6
[ -267 204 -3 ]
</pre>
 
=={{header|R}}==
<syntaxhighlight lang="rsplus">#===============================================================
<lang r>a <- c( 3.0, 4.0, 5.0)
# Vector products
b <- c( 4.0, 3.0, 5.0)
# R implementation
#===============================================================
 
crossa <- functionc(a3, 4, b5)
b <- c(a[2]*b[3] -4, a[3]*b[2], 5)
c <- c(-5, -12, -13)
a[3]*b[1] - a[1]*b[3],
 
a[1]*b[2] - a[2]*b[1])
#---------------------------------------------------------------
# Dot product
#---------------------------------------------------------------
 
dotp <- function(x, y) {
if (length(x) == length(y)) {
sum(x*y)
}
}
 
#---------------------------------------------------------------
# Cross product
#---------------------------------------------------------------
 
crossp <- function(x, y) {
if (length(x) == 3 && length(y) == 3) {
c(x[2]*y[3] - x[3]*y[2], x[3]*y[1] - x[1]*y[3], x[1]*y[2] - x[2]*y[1])
}
}
 
#---------------------------------------------------------------
# Scalar triple product
#---------------------------------------------------------------
 
scalartriplep <- function(x, y, z) {
if (length(x) == 3 && length(y) == 3 && length(z) == 3) {
dotp(x, crossp(y, z))
}
}
 
#---------------------------------------------------------------
# Vector triple product
#---------------------------------------------------------------
 
vectortriplep <- function(x, y, z) {
if (length(x) == 3 && length(y) == 3 && length(z) == 3) {
crosssp(x, crossp(y, z))
}
}
 
#---------------------------------------------------------------
# Compute and print
#---------------------------------------------------------------
 
cat("a . b =", dotp(a, b))
cat("a x b =", crossp(a, b))
cat("a . (b x c) =", scalartriplep(a, b, c))
cat("a x (b x c) =", vectortriplep(a, b, c))</syntaxhighlight>
 
{{out}}
<pre>a . b = 49
a x b = 5 5 -7
a . (b x c) = 6
a x (b x c) = -267 204 -3</pre>
 
'''Note:''' R has built-in functions for vector and matrix multiplications. Examples: "crossprod", %*% for inner and %o% for outer product.
cross(a, b)
# [1] 5 5 -7</lang>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 2,204 ⟶ 4,635:
(printf "A . B x C = ~s\n" (scalar-triple-product A B C))
(printf "A x B x C = ~s\n" (vector-triple-product A B C))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo|2015-11-24}}
<syntaxhighlight lang="raku" line>sub infix:<⋅> { [+] @^a »*« @^b }
 
sub infix:<⨯>([$a1, $a2, $a3], [$b1, $b2, $b3]) {
[ $a2*$b3 - $a3*$b2,
$a3*$b1 - $a1*$b3,
$a1*$b2 - $a2*$b1 ];
}
 
sub scalar-triple-product { @^a ⋅ (@^b ⨯ @^c) }
sub vector-triple-product { @^a ⨯ (@^b ⨯ @^c) }
 
my @a = <3 4 5>;
my @b = <4 3 5>;
my @c = <-5 -12 -13>;
 
say (:@a, :@b, :@c);
say "a ⋅ b = { @a ⋅ @b }";
say "a ⨯ b = <{ @a ⨯ @b }>";
say "a ⋅ (b ⨯ c) = { scalar-triple-product(@a, @b, @c) }";
say "a ⨯ (b ⨯ c) = <{ vector-triple-product(@a, @b, @c) }>";</syntaxhighlight>
{{out}}
<pre>("a" => ["3", "4", "5"], "b" => ["4", "3", "5"], "c" => ["-5", "-12", "-13"])
a ⋅ b = 49
a ⨯ b = <5 5 -7>
a ⋅ (b ⨯ c) = 6
a ⨯ (b ⨯ c) = <-267 204 -3></pre>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program computes the products: the dot, cross, scalar producttriple, and vector triple.*/
a= 3 4 5
/* the cross product, */
/*b= 4 3 5 /*(positive numbers don't need the scalar triple product, andquotes.)*/
c= '-5 -12 -13'
/* the vector triple product. */
Call tellV 'vector A =', a /*show the A vector, aligned numbers.*/
Call tellV "vector B =", b /* " " B " " " */
Call tellV "vector C =", c /* " " C " " " */
Say ''
Call tellV ' dot product [A·B] =', dot(a,b)
Call tellV 'cross product [AxB] =', cross(a,b)
Call tellV 'scalar triple product [A·(BxC)] =', dot(a,cross(b,c))
Call tellV 'vector triple product [Ax(BxC)] =', cross(a,cross(b,c))
Exit /*stick a fork in it, we're all done. */
/*---------------------------------------------------------------------------*/
cross: Procedure
Arg a b c, u v w
Return b*w-c*v c*u-a*w a*v-b*u
dot: Procedure
Arg a b c, u v w
Return a*u + b*v + c*w
/*---------------------------------------------------------------------------*/
tellV: Procedure
Parse Arg name,x y z
w=max(4,length(x),length(y),length(z)) /*max width */
Say right(name,33) right(x,w) right(y,w) right(z,w) /*show vector. */
Return</syntaxhighlight>
{{out|output|text=&nbsp; when using the default internal inputs:}}
<pre>
vector A = 3 4 5
vector B = 4 3 5
vector C = -5 -12 -13
 
a = 3 4 5 dot product [AÀB] = /*positive numbers don't need " */49
b = 4 3 cross product [AxB] = 5 5 -7
scalar triple product [AÀ(BxC)] = 6
c = "-5 -12 -13"
vector triple product [Ax(BxC)] = -267 204 -3</pre>
 
=={{header|Ring}}==
call tellV 'vector A =',a /*show the A vector, aligned #s*/
<syntaxhighlight lang="ring">
call tellV 'vector B =',b /*show the B vector, aligned #s*/
# Project : Vector products
call tellV 'vector C =',c /*show the C vector, aligned #s*/
say
call tellV ' dot product [A∙B] =',dot(a,b)
call tellV 'cross product [AxB] =',cross(a,b)
call tellV 'scalar triple product [A∙(BxC)] =',dot(a,cross(b,c))
call tellV 'vector triple product [Ax(BxC)] =',cross(a,cross(b,c))
exit /*stick a fork in it, we're done.*/
/*─────────────────────────────────────cross subroutine─────────────────*/
cross: procedure; parse arg x1 x2 x3,y1 y2 y3 /*the CROSS product.*/
return x2*y3-x3*y2 x3*y1-x1*y3 x1*y2-x2*y1 /*a vector quantity.*/
/*─────────────────────────────────────dot subroutine───────────────────*/
dot: procedure; parse arg x1 x2 x3,y1 y2 y3 /*the DOT product.*/
return x1*y1 + x2*y2 + x3*y3 /*a scaler quantity.*/
/*─────────────────────────────────────tellV subroutine─────────────────*/
tellV: procedure; parse arg name,x y z /*display the vector*/
w=max(4,length(x),length(y),length(z)) /*max width of nums.*/
say right(name,40) right(x,w) right(y,w) right(z,w)
return</lang>
'''out0ut'''
<pre style="height:25ex;overflow:scroll">
vector A = 3 4 5
vector B = 4 3 5
vector C = -5 -12 -13
 
d = list(3)
dot product [A∙B] = 49
e = list(3)
cross product [AxB] = 5 5 -7
a = [3, 4, 5]
scalar triple product [A∙(BxC)] = 6
b = [4, 3, 5]
vector triple product [Ax(BxC)] = -267 204 -3
c = [-5, -12, -13]
see "a . b = " + dot(a,b) + nl
cross(a,b,d)
see "a x b = (" + d[1] + ", " + d[2] + ", " + d[3] + ")" + nl
see "a . (b x c) = " + scalartriple(a,b,c) + nl
vectortriple(a,b,c,d)
def dot(a,b)
sum = 0
for n=1 to len(a)
sum = sum + a[n]*b[n]
next
return sum
func cross(a,b,d)
d = [a[2]*b[3]-a[3]*b[2], a[3]*b[1]-a[1]*b[3], a[1]*b[2]-a[2]*b[1]]
func scalartriple(a,b,c)
cross(b,c,d)
return dot(a,d)
func vectortriple(a,b,c,d)
cross(b,c,d)
cross(a,d,e)
see "a x (b x c) = (" + e[1] + ", " +e[2] + ", " + e[3] + ")"
</syntaxhighlight>
Output:
<pre>
a . b = 49
a x b = (5, 5, -7)
a . (b x c) = 6
a x (b x c) = (-267, 204, -3)
</pre>
 
=={{header|RPL}}==
Dot and cross products are built-in functions in RPL.
{{works with|Halcyon Calc|4.2.7}}
≪ → a b c
≪ a b DOT
a b CROSS
a b c CROSS DOT
a b c CROSS CROSS
≫ ≫
‘VPROD’ STO
 
[3 4 5] [4 3 5] [-5 -12 -13] VPROD
{{out}}
<pre>
4: 49
3: [ 5 5 -7 ]
2: 6
1: [ -267 204 -3 ]
</pre>
 
=={{header|Ruby}}==
Dot product is also known as ''inner product''. The standard library already defines Vector#inner_product and Vector# cross_product, so this program only defines the other threetwo methods.
<langsyntaxhighlight lang="ruby">require 'matrix'
 
class Vector
def cross_product(v)
unless size == 3 && v.size == 3
raise ArgumentError, "Vectors must have size 3"
end
Vector[self[1] * v[2] - self[2] * v[1],
self[2] * v[0] - self[0] * v[2],
self[0] * v[1] - self[1] * v[0]]
end
 
def scalar_triple_product(b, c)
self.inner_product(b.cross_product c)
Line 2,278 ⟶ 4,789:
puts "a cross b = #{a.cross_product b}"
puts "a dot (b cross c) = #{a.scalar_triple_product b, c}"
puts "a cross (b cross c) = #{a.vector_triple_product b, c}"</langsyntaxhighlight>
Output: <pre>a dot b = 49
a cross b = Vector[5, 5, -7]
a dot (b cross c) = 6
a cross (b cross c) = Vector[-267, 204, -3]</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">#[derive(Debug)]
struct Vector {
x: f64,
y: f64,
z: f64,
}
 
impl Vector {
fn new(x: f64, y: f64, z: f64) -> Self {
Vector {
x: x,
y: y,
z: z,
}
}
 
fn dot_product(&self, other: &Vector) -> f64 {
(self.x * other.x) + (self.y * other.y) + (self.z * other.z)
}
 
fn cross_product(&self, other: &Vector) -> Vector {
Vector::new(self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x)
}
 
fn scalar_triple_product(&self, b: &Vector, c: &Vector) -> f64 {
self.dot_product(&b.cross_product(&c))
}
 
fn vector_triple_product(&self, b: &Vector, c: &Vector) -> Vector {
self.cross_product(&b.cross_product(&c))
}
}
 
fn main(){
let a = Vector::new(3.0, 4.0, 5.0);
let b = Vector::new(4.0, 3.0, 5.0);
let c = Vector::new(-5.0, -12.0, -13.0);
 
println!("a . b = {}", a.dot_product(&b));
println!("a x b = {:?}", a.cross_product(&b));
println!("a . (b x c) = {}", a.scalar_triple_product(&b, &c));
println!("a x (b x c) = {:?}", a.vector_triple_product(&b, &c));
}</syntaxhighlight>
 
Output:<pre>a . b = 49
a x b = Vector { x: 5, y: 5, z: -7 }
a . (b x c) = 6
a x (b x c) = Vector { x: -267, y: 204, z: -3 }</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">case class Vector3D(x:Double, y:Double, z:Double) {
def dot(v:Vector3D):Double=x*v.x + y*v.y + z*v.z;
def cross(v:Vector3D)=Vector3D(y*v.z - z*v.y, z*v.x - x*v.z, x*v.y - y*v.x)
Line 2,303 ⟶ 4,866:
println("a x (b x c) : " + (a vectorTriple(b, c)))
}
}</langsyntaxhighlight>
{{out}}
<pre> a . b : 49.0
Line 2,314 ⟶ 4,877:
{{works with|Gauche}}
Using modified dot-product function from the [[Dot product]] task.
<langsyntaxhighlight lang="scheme">(define (dot-product A B)
(apply + (map * (vector->list A) (vector->list B))))
 
Line 2,348 ⟶ 4,911:
(display "A x B = ")(display (cross-product A B))(newline)
(display "A . B x C = ")(display (scalar-triple-product A B C))(newline)
(display "A x B x C = ") (display (vector-triple-product A B C))(newline)</langsyntaxhighlight>
Output:<pre>A = #(3 4 5)
B = #(4 3 5)
Line 2,361 ⟶ 4,924:
The program below uses Seed7s capaibility to define operator symbols.
The operators ''dot'' and ''X'' are defined with with priority 6 and assiciativity left-to-right.
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
 
Line 2,411 ⟶ 4,974:
writeln("a .(b x c) = " <& scalarTriple(a, b, c));
writeln("a x(b x c) = " <& vectorTriple(a, b, c));
end func;</langsyntaxhighlight>
 
{{output}}
<pre>
a = (3.0, 4.0, 5.0), b = (4.0, 3.0, 5.0), c = (-5.0, -12.0, -13.0)
a . b = 49.0
a x b = (5.0, 5.0, -7.0)
a .(b x c) = 6.0
a x(b x c) = (-267.0, 204.0, -3.0)
</pre>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">class MyVector(x, y, z) {
method ∙(vec) {
[self{:x,:y,:z}] »*« [vec{:x,:y,:z}] «+»
}
 
method ⨉(vec) {
MyVector(self.y*vec.z - self.z*vec.y,
self.z*vec.x - self.x*vec.z,
self.x*vec.y - self.y*vec.x)
}
 
method to_s {
"(#{x}, #{y}, #{z})"
}
}
 
var a = MyVector(3, 4, 5)
var b = MyVector(4, 3, 5)
var c = MyVector(-5, -12, -13)
 
say "a=#{a}; b=#{b}; c=#{c};"
say "a ∙ b = #{a ∙ b}"
say "a ⨉ b = #{a ⨉ b}"
say "a ∙ (b ⨉ c) = #{a ∙ (b ⨉ c)}"
say "a ⨉ (b ⨉ c) = #{a ⨉ (b ⨉ c)}"</syntaxhighlight>
{{out}}
<pre>a=(3, 4, 5); b=(4, 3, 5); c=(-5, -12, -13);
a ∙ b = 49
a ⨉ b = (5, 5, -7)
a ∙ (b ⨉ c) = 6
a ⨉ (b ⨉ c) = (-267, 204, -3)</pre>
=={{header|Simula}}==
{{Trans|C}}
<syntaxhighlight lang="simula">BEGIN
CLASS VECTOR(I,J,K); REAL I,J,K;;
REAL PROCEDURE DOTPRODUCT(A,B); REF(VECTOR) A,B;
DOTPRODUCT := A.I*B.I+A.J*B.J+A.K*B.K;
REF(VECTOR) PROCEDURE CROSSPRODUCT(A,B); REF(VECTOR) A,B;
CROSSPRODUCT :- NEW VECTOR(A.J*B.K - A.K*B.J,
A.K*B.I - A.I*B.K,
A.I*B.J - A.J*B.I);
REAL PROCEDURE SCALARTRIPLEPRODUCT(A,B,C); REF(VECTOR) A,B,C;
SCALARTRIPLEPRODUCT := DOTPRODUCT(A,CROSSPRODUCT(B,C));
REF(VECTOR) PROCEDURE VECTORTRIPLEPRODUCT(A,B,C); REF(VECTOR) A,B,C;
VECTORTRIPLEPRODUCT :- CROSSPRODUCT(A,CROSSPRODUCT(B,C));
PROCEDURE OUTR(X); REAL X;
OUTFIX(X,6,0);
 
PROCEDURE OUTVECTOR(A); REF(VECTOR) A;
BEGIN
OUTTEXT("("); OUTR(A.I);
OUTTEXT(", "); OUTR(A.J);
OUTTEXT(", "); OUTR(A.K); OUTTEXT(")");
END;
BEGIN
REF(VECTOR) A,B,C;
 
A :- NEW VECTOR(3, 4, 5);
B :- NEW VECTOR(4, 3, 5);
C :- NEW VECTOR(-5, -12, -13);
OUTTEXT("A = "); OUTVECTOR(A);
OUTIMAGE;
OUTTEXT("B = "); OUTVECTOR(B);
OUTIMAGE;
OUTTEXT("C = "); OUTVECTOR(C);
OUTIMAGE;
OUTTEXT("A . B = "); OUTR(DOTPRODUCT(A,B));
OUTIMAGE;
OUTTEXT("A X B = "); OUTVECTOR(CROSSPRODUCT(A,B));
OUTIMAGE;
OUTTEXT("A . (B X C) = "); OUTR(SCALARTRIPLEPRODUCT(A,B,C));
OUTIMAGE;
OUTTEXT("A X (B X C) = "); OUTVECTOR(VECTORTRIPLEPRODUCT(A,B,C));
OUTIMAGE;
END;
END;</syntaxhighlight>
{{out}}
<pre>A = (3.000000, 4.000000, 5.000000)
B = (4.000000, 3.000000, 5.000000)
C = (-5.000000, -12.000000, -13.000000)
A . B = 49.000000
A X B = (5.000000, 5.000000, -7.000000)
A . (B X C) = 6.000000
A X (B X C) = (-267.000000, 204.000000, -3.000000)
</pre>
 
=={{header|Stata}}==
<syntaxhighlight lang="stata">mata
real scalar sprod(real colvector u, real colvector v) {
return(u[1]*v[1] + u[2]*v[2] + u[3]*v[3])
}
 
real colvector vprod(real colvector u, real colvector v) {
return(u[2]*v[3]-u[3]*v[2]\u[3]*v[1]-u[1]*v[3]\u[1]*v[2]-u[2]*v[1])
}
 
real scalar striple(real colvector u, real colvector v, real colvector w) {
return(sprod(u, vprod(v, w)))
}
 
real colvector vtriple(real colvector u, real colvector v, real colvector w) {
return(vprod(u, vprod(v, w)))
}
 
a = 3\4\5
b = 4\3\5
c = -5\-12\-13
 
sprod(a, b)
49
 
vprod(a, b)
1
+------+
1 | 5 |
2 | 5 |
3 | -7 |
+------+
 
striple(a, b, c)
6
 
vtriple(a, b, c)
1
+--------+
1 | -267 |
2 | 204 |
3 | -3 |
+--------+
end</syntaxhighlight>
 
=={{header|Swift}}==
 
<syntaxhighlight lang="swift">import Foundation
 
infix operator • : MultiplicationPrecedence
infix operator × : MultiplicationPrecedence
 
public struct Vector {
public var x = 0.0
public var y = 0.0
public var z = 0.0
 
public init(x: Double, y: Double, z: Double) {
(self.x, self.y, self.z) = (x, y, z)
}
 
public static func • (lhs: Vector, rhs: Vector) -> Double {
return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z
}
 
public static func × (lhs: Vector, rhs: Vector) -> Vector {
return Vector(
x: lhs.y * rhs.z - lhs.z * rhs.y,
y: lhs.z * rhs.x - lhs.x * rhs.z,
z: lhs.x * rhs.y - lhs.y * rhs.x
)
}
}
 
let a = Vector(x: 3, y: 4, z: 5)
let b = Vector(x: 4, y: 3, z: 5)
let c = Vector(x: -5, y: -12, z: -13)
 
print("a: \(a)")
print("b: \(b)")
print("c: \(c)")
print()
print("a • b = \(a • b)")
print("a × b = \(a × b)")
print("a • (b × c) = \(a • (b × c))")
print("a × (b × c) = \(a × (b × c))")</syntaxhighlight>
 
{{out}}
 
<pre>a: Vector(x: 3.0, y: 4.0, z: 5.0)
b: Vector(x: 4.0, y: 3.0, z: 5.0)
c: Vector(x: -5.0, y: -12.0, z: -13.0)
 
a • b = 49.0
a × b = Vector(x: 5.0, y: 5.0, z: -7.0)
a • (b × c) = 6.0
a × (b × c) = Vector(x: -267.0, y: 204.0, z: -3.0)</pre>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc dot {A B} {
lassign $A a1 a2 a3
lassign $B b1 b2 b3
Line 2,431 ⟶ 5,196:
proc vectorTriple {A B C} {
cross $A [cross $B $C]
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">set a {3 4 5}
set b {4 3 5}
set c {-5 -12 -13}
Line 2,439 ⟶ 5,204:
puts "a x b = [cross $a $b]"
puts "a • b x c = [scalarTriple $a $b $c]"
puts "a x b x c = [vectorTriple $a $b $c]"</langsyntaxhighlight>
Output:<pre>a • b = 49
a x b = 5 5 -7
Line 2,445 ⟶ 5,210:
a x b x c = -267 204 -3
</pre>
 
=={{header|uBasic/4tH}}==
{{Trans|BBC BASIC}}
Since uBasic/4tH has only one single array, we use its variables to hold the offsets of the vectors. A similar problem arises when local vectors are required.
<syntaxhighlight lang="text">a = 0 ' use variables for vector addresses
b = a + 3
c = b + 3
d = c + 3
 
Proc _Vector (a, 3, 4, 5) ' initialize the vectors
Proc _Vector (b, 4, 3, 5)
Proc _Vector (c, -5, -12, -13)
 
Print "a . b = "; FUNC(_FNdot(a, b))
Proc _Cross (a, b, d)
Print "a x b = (";@(d+0);", ";@(d+1);", ";@(d+2);")"
Print "a . (b x c) = "; FUNC(_FNscalarTriple(a, b, c))
Proc _VectorTriple (a, b, c, d)
Print "a x (b x c) = (";@(d+0);", ";@(d+1);", ";@(d+2);")"
End
 
_FNdot Param (2)
Return ((@(a@+0)*@(b@+0))+(@(a@+1)*@(b@+1))+(@(a@+2)*@(b@+2)))
 
_Vector Param (4) ' initialize a vector
@(a@ + 0) = b@
@(a@ + 1) = c@
@(a@ + 2) = d@
Return
 
_Cross Param (3)
@(c@+0) = @(a@ + 1) * @(b@ + 2) - @(a@ + 2) * @(b@ + 1)
@(c@+1) = @(a@ + 2) * @(b@ + 0) - @(a@ + 0) * @(b@ + 2)
@(c@+2) = @(a@ + 0) * @(b@ + 1) - @(a@ + 1) * @(b@ + 0)
Return
 
_FNscalarTriple Param (3)
Local (1) ' a "local" vector
d@ = d + 3 ' (best effort) ;-)
Proc _Cross(b@, c@, d@)
Return (FUNC(_FNdot(a@, d@)))
 
_VectorTriple Param(4)
Local (1) ' a "local" vector
e@ = d + 3 ' (best effort) ;-)
Proc _Cross (b@, c@, e@)
Proc _Cross (a@, e@, d@)
Return</syntaxhighlight>
{{Out}}
<pre>a . b = 49
a x b = (5, 5, -7)
a . (b x c) = 6
a x (b x c) = (-267, 204, -3)
 
0 OK, 0:1370</pre>
 
=={{header|VBA}}==
{{trans|Phix}}<syntaxhighlight lang="vb">Option Base 1
Function dot_product(a As Variant, b As Variant) As Variant
dot_product = WorksheetFunction.SumProduct(a, b)
End Function
Function cross_product(a As Variant, b As Variant) As Variant
cross_product = Array(a(2) * b(3) - a(3) * b(2), a(3) * b(1) - a(1) * b(3), a(1) * b(2) - a(2) * b(1))
End Function
Function scalar_triple_product(a As Variant, b As Variant, c As Variant) As Variant
scalar_triple_product = dot_product(a, cross_product(b, c))
End Function
Function vector_triple_product(a As Variant, b As Variant, c As Variant) As Variant
vector_triple_product = cross_product(a, cross_product(b, c))
End Function
Public Sub main()
a = [{3, 4, 5}]
b = [{4, 3, 5}]
c = [{-5, -12, -13}]
Debug.Print " a . b = "; dot_product(a, b)
Debug.Print " a x b = "; "("; Join(cross_product(a, b), ", "); ")"
Debug.Print "a . (b x c) = "; scalar_triple_product(a, b, c)
Debug.Print "a x (b x c) = "; "("; Join(vector_triple_product(a, b, c), ", "); ")"
End Sub</syntaxhighlight>{{out}}
<pre> a . b = 49
a x b = (5, 5, -7)
a . (b x c) = 6
a x (b x c) = (-267, 204, -3)</pre>
 
=={{header|Visual Basic .NET}}==
Class: Vector3D
<langsyntaxhighlight lang="vbnet">Public Class Vector3D
Private _x, _y, _z As Double
 
Line 2,505 ⟶ 5,357:
Return String.Format("({0}, {1}, {2})", _x, _y, _z)
End Function
End Class</langsyntaxhighlight>
Module: Module1
<langsyntaxhighlight lang="vbnet">Module Module1
 
Sub Main()
Line 2,525 ⟶ 5,377:
End Sub
 
End Module</langsyntaxhighlight>
Output:
<pre>v1: (3, 4, 5)
Line 2,535 ⟶ 5,387:
v1 . (v2 x v3) = 6
v1 x (v2 x v3) = (-267, 204, -3)</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">struct Vector {
x f64
y f64
z f64
}
const (
a = Vector{3, 4, 5}
b = Vector{4, 3, 5}
c = Vector{-5, -12, -13}
)
fn dot(a Vector, b Vector) f64 {
return a.x*b.x + a.y*b.y + a.z*b.z
}
fn cross(a Vector, b Vector) Vector {
return Vector{a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x}
}
fn s3(a Vector, b Vector, c Vector) f64 {
return dot(a, cross(b, c))
}
fn v3(a Vector, b Vector, c Vector) Vector {
return cross(a, cross(b, c))
}
fn main() {
println(dot(a, b))
println(cross(a, b))
println(s3(a, b, c))
println(v3(a, b, c))
}</syntaxhighlight>
 
{{out}}
<pre>
49.
Vector{
x: 5
y: 5
z: -7
}
6.
Vector{
x: -267
y: 204
z: -3
}
</pre>
 
=={{header|Wortel}}==
<langsyntaxhighlight lang="wortel">@let {
dot &[a b] @sum @mapm ^* [a b]
cross &[a b] [[
Line 2,557 ⟶ 5,462:
@!vectorTripleProduct [a b c]
]]
}</langsyntaxhighlight>
Returns:
<pre>[49 [5 5 -7] 6 [-267 204 -3]]</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
<syntaxhighlight lang="wren">class Vector3D {
construct new(x, y, z) {
if (x.type != Num || y.type != Num || z.type != Num) Fiber.abort("Arguments must be numbers.")
_x = x
_y = y
_z = z
}
 
x { _x }
y { _y }
z { _z }
 
dot(v) {
if (v.type != Vector3D) Fiber.abort("Argument must be a Vector3D.")
return _x * v.x + _y * v.y + _z * v.z
}
 
cross(v) {
if (v.type != Vector3D) Fiber.abort("Argument must be a Vector3D.")
return Vector3D.new(_y*v.z - _z*v.y, _z*v.x - _x*v.z, _x*v.y - _y*v.x)
}
 
scalarTriple(v, w) {
if ((v.type != Vector3D) || (w.type != Vector3D)) Fiber.abort("Arguments must be Vector3Ds.")
return this.dot(v.cross(w))
}
 
vectorTriple(v, w) {
if ((v.type != Vector3D) || (w.type != Vector3D)) Fiber.abort("Arguments must be Vector3Ds.")
return this.cross(v.cross(w))
}
 
toString { [_x, _y, _z].toString }
}
 
var a = Vector3D.new(3, 4, 5)
var b = Vector3D.new(4, 3, 5)
var c = Vector3D.new(-5, -12, -13)
System.print("a = %(a)")
System.print("b = %(b)")
System.print("c = %(c)")
System.print()
System.print("a . b = %(a.dot(b))")
System.print("a x b = %(a.cross(b))")
System.print("a . b x c = %(a.scalarTriple(b, c))")
System.print("a x b x c = %(a.vectorTriple(b, c))")</syntaxhighlight>
 
{{out}}
<pre>
a = [3, 4, 5]
b = [4, 3, 5]
c = [-5, -12, -13]
 
a . b = 49
a x b = [5, 5, -7]
a . b x c = 6
a x b x c = [-267, 204, -3]
</pre>
 
{{libheader|Wren-vector}}
Alternatively, using the above module to produce exactly the same output as before:
<syntaxhighlight lang="wren">import "./vector" for Vector3
 
var a = Vector3.new(3, 4, 5)
var b = Vector3.new(4, 3, 5)
var c = Vector3.new(-5, -12, -13)
System.print("a = %(a)")
System.print("b = %(b)")
System.print("c = %(c)")
System.print()
System.print("a . b = %(a.dot(b))")
System.print("a x b = %(a.cross(b))")
System.print("a . b x c = %(a.scalarTripleProd(b, c))")
System.print("a x b x c = %(a.vectorTripleProd(b, c))")</syntaxhighlight>
 
=={{header|XBS}}==
<syntaxhighlight lang="xbs">#> Vector3 Class <#
class Vector3 {
construct=func(self,x,y,z){
self:x=x;
self:y=y;
self:z=z;
};
ToString=func(self){
send self.x+", "+self.y+", "+self.z;
};
Magnitude=func(self){
send math.sqrt((self.x^2)+(self.y^2)+(self.z^2));
};
Normalize=func(self){
set Mag = self::Magnitude();
send new Vector3 with [self.x/Mag,self.y/Mag,self.z/Mag];
};
Dot=func(self,v2){
send (self.x*v2.x)+(self.y*v2.y)+(self.z*v2.z);
};
__add=func(self,x){
if (type(x)=="object"){
send new Vector3 with [self.x+x.x,self.y+x.y,self.z+x.z];
} else {
send new Vector3 with [self.x+x,self.y+x,self.z+x];
}
};
__sub=func(self,x){
if (type(x)=="object"){
send new Vector3 with [self.x-x.x,self.y-x.y,self.z-x.z];
} else {
send new Vector3 with [self.x-x,self.y-x,self.z-x];
}
};
__mul=func(self,x){
if (type(x)=="object"){
send new Vector3 with [self.x*x.x,self.y*x.y,self.z*x.z];
} else {
send new Vector3 with [self.x*x,self.y*x,self.z*x];
}
};
__div=func(self,x){
if (type(x)=="object"){
send new Vector3 with [self.x/x.x,self.y/x.y,self.z/x.z];
} else {
send new Vector3 with [self.x/x,self.y/x,self.z/x];
}
};
__pow=func(self,x){
if (type(x)=="object"){
send new Vector3 with [self.x^x.x,self.y^x.y,self.z^x.z];
} else {
send new Vector3 with [self.x^x,self.y^x,self.z^x];
}
};
__mod=func(self,x){
if (type(x)=="object"){
send new Vector3 with [self.x%x.x,self.y%x.y,self.z%x.z];
} else {
send new Vector3 with [self.x%x,self.y%x,self.z%x];
}
};
Reflect=func(self,v2){
set Normal = self::Normalize();
set Direction = v2::Normalize();
send (Normal*(2*Normal::Dot(Direction)))-Direction;
};
Cross=func(self,v2){
send new Vector3 with [(self.y*v2.z)-(self.z*v2.y),(self.z*v2.x)-(self.x*v2.z),(self.x*v2.y)-(self.y*v2.x)];
};
}
 
math:deg=func(x){
send x*(180/math.PI);
}
 
math:rad=func(x){
send x*(math.PI/180);
}
 
set a = new Vector3 with [3,4,5];
set b = new Vector3 with [4,3,5];
set c = new Vector3 with [-5,-12,-13];
 
log("Dot: ",a::Dot(b));
log("Cross: ",a::Cross(b)::ToString());
log("Scalar Triple: ",a::Dot(b::Cross(c)));
log("Vector Triple: ",a::Cross(b::Cross(c))::ToString());</syntaxhighlight>
{{out}}
<pre>
Dot: 49
Cross: 5, 5, -7
Scalar Triple: 6
Vector Triple: -267, 204, -3
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
 
func DotProd(A, B); \Return the dot product of two 3D vectors
Line 2,606 ⟶ 5,685:
IntOut(0, D(1)); ChOut(0, 9\tab\);
IntOut(0, D(2)); CrLf(0);
]</langsyntaxhighlight>
 
Output:
Line 2,615 ⟶ 5,694:
-267 204 -3
</pre>
 
=={{header|zkl}}==
Since the input vectors are all int, the output is int. For a float output, use float data (or convert) in the input vectors and change sum() to sum(0.0) (in dotp).
 
The [(a1,a2,a3)] parameter notation just means add a preamble to the function body to do list assignment: a1,a2,a3:=arglist[0]. Since we don't need the vector as such, don't bother to name it (in the parameter list)
<syntaxhighlight lang="zkl">fcn dotp(a,b){ a.zipWith('*,b).sum() } //1 slow but concise
fcn crossp([(a1,a2,a3)],[(b1,b2,b3)]) //2
{ return(a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1) }</syntaxhighlight>
<syntaxhighlight lang="zkl">a,b,c := T(3,4,5), T(4,3,5), T(-5,-12,-13);
dotp(a,b).println(); //5 --> 49
crossp(a,b).println(); //6 --> (5,5,-7)
dotp(a, crossp(b,c)).println(); //7 --> 6
crossp(a, crossp(b,c)).println(); //8 --> (-267,204,-3)</syntaxhighlight>
{{out}}
<pre>
49
L(5,5,-7)
6
L(-267,204,-3)
</pre>
Or, using the GNU Scientific Library:
<syntaxhighlight lang="zkl">var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
a:=GSL.VectorFromData( 3, 4, 5);
b:=GSL.VectorFromData( 4, 3, 5);
c:=GSL.VectorFromData(-5,-12,-13);
 
(a*b).println(); // 49, dot product
a.copy().crossProduct(b) // (5,5,-7) cross product, in place
.format().println();
(a*(b.copy().crossProduct(c))).println(); // 6 scalar triple product
(a.crossProduct(b.crossProduct(c))) // (-267,204,-3) vector triple product, in place
.format().println();</syntaxhighlight>
{{out}}
<pre>
49
5.00,5.00,-7.00
6
-267.00,204.00,-3.00
</pre>
 
[[Category:Geometry]]
222

edits