Vector: Difference between revisions

31,702 bytes added ,  1 month ago
m
Update Lang example: Use new struct definition syntax
No edit summary
m (Update Lang example: Use new struct definition syntax)
 
(37 intermediate revisions by 25 users not shown)
Line 12:
The four operations to be implemented are:
* Vector <big><b> + </b></big> Vector addition
* Vector <big><b> - </b></big> VlectorVector subtraction
* Vector <big><b> * </b></big> scalar multiplication
* Vector <big><b> / </b></big> scalar division
<br><br>
 
=={{header|11l}}==
{{trans|D}}
 
<syntaxhighlight lang="11l">T Vector
Float x, y
 
F (x, y)
.x = x
.y = y
 
F +(vector)
R Vector(.x + vector.x, .y + vector.y)
 
F -(vector)
R Vector(.x - vector.x, .y - vector.y)
 
F *(mult)
R Vector(.x * mult, .y * mult)
 
F /(denom)
R Vector(.x / denom, .y / denom)
 
F String()
R ‘(#., #.)’.format(.x, .y)
 
print(Vector(5, 7) + Vector(2, 3))
print(Vector(5, 7) - Vector(2, 3))
print(Vector(5, 7) * 11)
print(Vector(5, 7) / 2)</syntaxhighlight>
 
{{out}}
<pre>
(7, 10)
(3, 4)
(55, 77)
(2.5, 3.5)
</pre>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
 
DEFINE X_="+0"
DEFINE Y_="+6"
 
TYPE Vector=[CARD x1,x2,x3,y1,y2,y3]
 
PROC PrintVec(Vector POINTER v)
Print("[") PrintR(v X_)
Print(",") PrintR(v Y_) Print("]")
RETURN
 
PROC VecIntInit(Vector POINTER v INT ix,iy)
IntToReal(ix,v X_)
IntToReal(iy,v Y_)
RETURN
 
PROC VecRealInit(Vector POINTER v REAL POINTER rx,ry)
RealAssign(rx,v X_)
RealAssign(ry,v Y_)
RETURN
 
PROC VecStringInit(Vector POINTER v CHAR ARRAY sx,sy)
ValR(sx,v X_)
ValR(sy,v Y_)
RETURN
 
PROC VecAdd(Vector POINTER v1,v2,res)
RealAdd(v1 X_,v2 X_,res X_) ;res.x=v1.x+v2.x
RealAdd(v1 Y_,v2 Y_,res Y_) ;res.y=v1.y+v2.y
RETURN
 
PROC VecSub(Vector POINTER v1,v2,res)
RealSub(v1 X_,v2 X_,res X_) ;res.x=v1.x-v2.x
RealSub(v1 Y_,v2 Y_,res Y_) ;res.y=v1.y-v2.y
RETURN
 
PROC VecMult(Vector POINTER v REAL POINTER a Vector POINTER res)
RealMult(v X_,a,res X_) ;res.x=v.x*a
RealMult(v Y_,a,res Y_) ;res.y=v.y*a
RETURN
 
PROC VecDiv(Vector POINTER v REAL POINTER a Vector POINTER res)
RealDiv(v X_,a,res X_) ;res.x=v.x/a
RealDiv(v Y_,a,res Y_) ;res.y=v.y/a
RETURN
 
PROC Main()
Vector v1,v2,res
REAL s
 
Put(125) PutE() ;clear the screen
VecStringInit(v1,"12.3","-4.56")
VecStringInit(v2,"9.87","654.3")
ValR("0.1",s)
 
VecAdd(v1,v2,res)
PrintVec(v1) Print(" + ") PrintVec(v2)
Print(" =") PutE() PrintVec(res) PutE() PutE()
 
VecSub(v1,v2,res)
PrintVec(v1) Print(" - ") PrintVec(v2)
Print(" =") PutE() PrintVec(res) PutE() PutE()
 
VecMult(v1,s,res)
PrintVec(v1) Print(" * ") PrintR(s)
Print(" = ") PrintVec(res) PutE() PutE()
 
VecDiv(v1,s,res)
PrintVec(v1) Print(" / ") PrintR(s)
Print(" = ") PrintVec(res)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Vector.png Screenshot from Atari 8-bit computer]
<pre>
[12.3,-4.56] + [9.87,654.3] = [22.17,649.74]
 
[12.3,-4.56] - [9.87,654.3] = [2.43,-658.86]
 
[12.3,-4.56] * .1 = [1.23,-0.456]
 
[12.3,-4.56] / .1 = [123,-45.6]
</pre>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68"># the standard mode COMPLEX is a two element vector #
MODE VECTOR = COMPLEX;
# the operations required for the task plus many others are provided as standard for COMPLEX and REAL items #
Line 34 ⟶ 158:
print( ( "a*11: ", TOSTRING ( a * 11 ), newline ) );
print( ( "a/2 : ", TOSTRING ( a / 2 ), newline ) )
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 42 ⟶ 166:
a/2 : [2.5000, 3.5000]
</pre>
 
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">define :vector [
x y
][
print: -> render "(|this\x|, |this\y|)" ; prettyprint function
]
 
ensureVector: function [block][
ensure -> every? @block => [is? :vector &]
]
 
vadd: function [a b][
ensureVector [a b]
to :vector @[a\x + b\x, a\y + b\y]
]
 
vsub: function [a b][
ensureVector [a b]
to :vector @[a\x - b\x, a\y - b\y]
]
 
vmul: function [a n][
ensureVector [a]
to :vector @[a\x * n, a\y * n]
]
 
vdiv: function [a n][
ensureVector [a]
to :vector @[a\x // n, a\y // n]
]
 
; test our vector object
a: to :vector [5 7]
b: to :vector [2 3]
print [a '+ b '= vadd a b]
print [a '- b '= vsub a b]
print [a '* 11 '= vmul a 11]
print [a '/ 11 '= vdiv a 2]</syntaxhighlight>
 
{{out}}
 
<pre>(5, 7) + (2, 3) = (7, 10)
(5, 7) - (2, 3) = (3, 4)
(5, 7) * 11 = (55, 77)
(5, 7) / 11 = (2.5, 3.5)</pre>
 
=={{header|BASIC}}==
==={{header|BASIC256}}===
{{trans|Ring}}
<syntaxhighlight lang="freebasic">arraybase 1
dim vect1(2)
vect1[1] = 5 : vect1[2] = 7
dim vect2(2)
vect2[1] = 2 : vect2[2] = 3
dim vect3(vect1[?])
 
subroutine showarray(vect3)
print "[";
svect$ = ""
for n = 1 to vect3[?]
svect$ &= vect3[n] & ", "
next n
svect$ = left(svect$, length(svect$) - 2)
print svect$;
print "]"
end subroutine
 
for n = 1 to vect1[?]
vect3[n] = vect1[n] + vect2[n]
next n
print "[" & vect1[1] & ", " & vect1[2] & "] + [" & vect2[1] & ", " & vect2[2] & "] = ";
call showarray(vect3)
 
for n = 1 to vect1[?]
vect3[n] = vect1[n] - vect2[n]
next n
print "[" & vect1[1] & ", " & vect1[2] & "] - [" & vect2[1] & ", " & vect2[2] & "] = ";
call showarray(vect3)
 
for n = 1 to vect1[?]
vect3[n] = vect1[n] * 11
next n
print "[" & vect1[1] & ", " & vect1[2] & "] * " & 11 & " = ";
call showarray(vect3)
 
for n = 1 to vect1[?]
vect3[n] = vect1[n] / 2
next n
print "[" & vect1[1] & ", " & vect1[2] & "] / " & 2 & " = ";
call showarray(vect3)
end</syntaxhighlight>
{{out}}
<pre>[5, 7] + [2, 3] = [7, 10]
[5, 7] - [2, 3] = [3, 4]
[5, 7] * 11 = [55, 77]
[5, 7] / 2 = [2.5, 3.5]</pre>
 
=={{header|BQN}}==
BQN's arrays are treated like vectors by default, and all arithmetic operations vectorize when given appropriate length arguments. This means that vector functionality is a builtin-in feature of BQN.
 
<syntaxhighlight lang="bqn"> 5‿7 + 2‿3
⟨7 10⟩
5‿7 - 2‿3
⟨3 4⟩
5‿7 × 11
⟨55 77⟩
5‿7 ÷ 2
⟨2.5 3.5⟩</syntaxhighlight>
 
=={{header|C}}==
j cap or hat j is not part of the ASCII set, thus û ( 150 ) is used in it's place.
<syntaxhighlight lang="c">
<lang C>
#include<stdio.h>
#include<math.h>
Line 129 ⟶ 362:
return 0;
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 147 ⟶ 380:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 202 ⟶ 435:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>[7,10]
Line 211 ⟶ 444:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <cmath>
#include <cassert>
Line 278 ⟶ 511:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
X: 1 Y: 1
</pre>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">% Parameterized vector class
vector = cluster [T: type] is make, add, sub, mul, div,
get_x, get_y, to_string
% The inner type must support basic math
where T has add: proctype (T,T) returns (T)
signals (overflow, underflow),
sub: proctype (T,T) returns (T)
signals (overflow, underflow),
mul: proctype (T,T) returns (T)
signals (overflow, underflow),
div: proctype (T,T) returns (T)
signals (zero_divide, overflow, underflow)
rep = struct [x,y: T]
% instantiate
make = proc (x,y: T) returns (cvt)
return(rep${x:x, y:y})
end make
% vector addition and subtraction
add = proc (a,b: cvt) returns (cvt)
signals (overflow, underflow)
return(rep${x: up(a).x + up(b).x,
y: up(a).y + up(b).y})
resignal overflow, underflow
end add
sub = proc (a,b: cvt) returns (cvt)
signals (overflow, underflow)
return(rep${x: up(a).x - up(b).x,
y: up(a).y - up(b).y})
resignal overflow, underflow
end sub
% scalar multiplication and division
mul = proc (a: cvt, b: T) returns (cvt)
signals (overflow, underflow)
return(rep${x: up(a).x*b, y: up(a).y*b})
resignal overflow, underflow
end mul
div = proc (a: cvt, b: T) returns (cvt)
signals (zero_divide, overflow, underflow)
return(rep${x: up(a).x/b, y: up(a).y/b})
resignal zero_divide, overflow, underflow
end div
% accessors
get_x = proc (v: cvt) returns (T) return(v.x) end get_x
get_y = proc (v: cvt) returns (T) return(v.y) end get_y
% we can't just use T$unparse for pretty-printing, since
% for floats it always prints the exponential form, and
% that's not very pretty.
% passing in a conversion function at the moment of
% generating the string form is the least bad way.
to_string = proc (v: cvt, f: proctype (T) returns (string))
returns (string)
return("(" || f(v.x) || ", " || f(v.y) || ")")
end to_string
end vector
% this function formats a real somewhat neatly without needing
% extra parameters
format_real = proc (r: real) returns (string)
return(f_form(r, 2, 4))
end format_real
 
start_up = proc ()
vr = vector[real] % use real numbers
po: stream := stream$primary_output()
% vectors
a: vr := vr$make(5.0, 7.0)
b: vr := vr$make(2.0, 3.0)
% do some math
a_plus_b: vr := a + b
a_minus_b: vr := a - b
a_times_11: vr := a * 11.0
a_div_2: vr := a / 2.0
% show the results
stream$putl(po, " a = " || vr$to_string(a, format_real))
stream$putl(po, " b = " || vr$to_string(b, format_real))
stream$putl(po, " a + b = " || vr$to_string(a_plus_b, format_real))
stream$putl(po, " a - b = " || vr$to_string(a_minus_b, format_real))
stream$putl(po, "a * 11 = " || vr$to_string(a_times_11, format_real))
stream$putl(po, " a / 2 = " || vr$to_string(a_div_2, format_real))
end start_up </syntaxhighlight>
{{out}}
<pre> a = (5.0000, 7.0000)
b = (2.0000, 3.0000)
a + b = (7.0000, 10.0000)
a - b = (3.0000, 4.0000)
a * 11 = (55.0000, 77.0000)
a / 2 = (2.5000, 3.5000)</pre>
 
=={{header|D}}==
<langsyntaxhighlight Dlang="d">import std.stdio;
 
void main() {
Line 323 ⟶ 655:
sink.formattedWrite!"(%s, %s)"(x, y);
}
}</langsyntaxhighlight>
 
{{out}}
Line 333 ⟶ 665:
=={{header|Delphi}}==
 
<syntaxhighlight lang="delphi">
<lang Delphi>
program Vector;
 
Line 364 ⟶ 696:
 
.
</syntaxhighlight>
</lang>
 
{{out}}
Line 372 ⟶ 704:
(55,0 + i77,0)
(2,5 + i3,5)
</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight>
func[] vadd a[] b[] .
for i to len a[]
r[] &= a[i] + b[i]
.
return r[]
.
func[] vsub a[] b[] .
for i to len a[]
r[] &= a[i] - b[i]
.
return r[]
.
func[] vmul a[] b .
for i to len a[]
r[] &= a[i] * b
.
return r[]
.
func[] vdiv a[] b .
for i to len a[]
r[] &= a[i] / b
.
return r[]
.
print vadd [ 5 7 ] [ 2 3 ]
print vsub [ 5 7 ] [ 2 3 ]
print vmul [ 5 7 ] 11
print vdiv [ 5 7 ] 2
</syntaxhighlight>
 
{{out}}
<pre>
[ 7 10 ]
[ 3 4 ]
[ 55 77 ]
[ 2.50 3.50 ]
</pre>
 
=={{header|F#|F sharp}}==
<langsyntaxhighlight lang="fsharp">open System
 
let add (ax, ay) (bx, by) =
Line 398 ⟶ 770:
printfn "%A" (mul a 11.0)
printfn "%A" (div a 2.0)
0 // return an integer exit code</langsyntaxhighlight>
 
=={{header|Factor}}==
It should be noted the <code>math.vectors</code> vocabulary has words for treating any sequence like a vector. For instance:
<langsyntaxhighlight lang="factor">(scratchpad) USE: math.vectors
(scratchpad) { 1 2 } { 3 4 } v+
 
--- Data stack:
{ 4 6 }</langsyntaxhighlight>
However, in the spirit of the task, we will implement our own vector data structure. In addition to arithmetic and prettyprinting, we define a convenient literal syntax for making new vectors.
<langsyntaxhighlight lang="factor">USING: accessors arrays kernel math parser prettyprint
prettyprint.custom sequences ;
IN: rosetta-code.vector
Line 437 ⟶ 809:
M: vec pprint-delims drop \ VEC{ \ } ;
M: vec >pprint-sequence parts 2array ;
M: vec pprint* pprint-object ;</langsyntaxhighlight>
We demonstrate the use of vectors in a new file, since parsing words can't be used in the same file where they're defined.
<langsyntaxhighlight lang="factor">USING: kernel formatting prettyprint rosetta-code.vector
sequences ;
IN: rosetta-code.vector
Line 455 ⟶ 827:
! course.
 
5 2 <vec> 1.3 [ v* ] demo</langsyntaxhighlight>
{{out}}
<pre>
Line 463 ⟶ 835:
VEC{ 5 7 } 2 v/ = VEC{ 2+1/2 3+1/2 }
VEC{ 5 2 } 1.3 v* = VEC{ 6.5 2.6 }
</pre>
 
 
 
=={{header|Forth}}==
 
{{works with|gforth|0.7.3}}
This is integer only implementation. A vector is two numbers on the stack. "pretty print" is just printing the two numbers in the desired order.
<syntaxhighlight lang="forth">: v. swap . . ;
: v* swap over * >r * r> ;
: v/ swap over / >r / r> ;
: v+ >r swap >r + r> r> + ;
: v- >r swap >r - r> r> - ;</syntaxhighlight>
 
{{out}}
As Forth is [[wp:Read–eval–print_loop|REPL]], to add (1 , 2) to (3 , 4), just type <code>1 2 3 4 v+ v.</code> (followed by [Enter]):
<pre>1 2 3 4 v+ v. 4 6 ok</pre>
To substract (1 , 4) from (3 , 5), just type <code>3 5 1 4 v- v.</code> (followed by [Enter]):
<pre>3 5 1 4 v- v. 2 1 ok</pre>
To multiply (2 , 4) by 3, just type <code>2 4 3 v* v.</code> (followed by [Enter]):
<pre>2 4 3 v* v. 6 12 ok</pre>
To divide (12 , 33) by 3, just type <code>12 33 3 v/ v.</code> (followed by [Enter]):
<pre>12 33 3 v/ v. 4 11 ok</pre>
 
 
 
=={{header|Fortran}}==
<syntaxhighlight lang="fortran">MODULE ROSETTA_VECTOR
IMPLICIT NONE
 
TYPE VECTOR
REAL :: X, Y
END TYPE VECTOR
 
 
INTERFACE OPERATOR(+)
MODULE PROCEDURE VECTOR_ADD
END INTERFACE
 
INTERFACE OPERATOR(-)
MODULE PROCEDURE VECTOR_SUB
END INTERFACE
 
INTERFACE OPERATOR(/)
MODULE PROCEDURE VECTOR_DIV
END INTERFACE
 
INTERFACE OPERATOR(*)
MODULE PROCEDURE VECTOR_MULT
END INTERFACE
 
CONTAINS
 
FUNCTION VECTOR_ADD(VECTOR_1, VECTOR_2)
TYPE(VECTOR), INTENT(IN) :: VECTOR_1, VECTOR_2
TYPE(VECTOR) :: VECTOR_ADD
VECTOR_ADD%X = VECTOR_1%X+VECTOR_2%X
VECTOR_ADD%Y = VECTOR_1%Y+VECTOR_2%Y
END FUNCTION VECTOR_ADD
 
FUNCTION VECTOR_SUB(VECTOR_1, VECTOR_2)
TYPE(VECTOR), INTENT(IN) :: VECTOR_1, VECTOR_2
TYPE(VECTOR) :: VECTOR_SUB
VECTOR_SUB%X = VECTOR_1%X-VECTOR_2%X
VECTOR_SUB%Y = VECTOR_1%Y-VECTOR_2%Y
END FUNCTION VECTOR_SUB
 
FUNCTION VECTOR_DIV(VEC, SCALAR)
TYPE(VECTOR), INTENT(IN) :: VEC
REAL, INTENT(IN) :: SCALAR
TYPE(VECTOR) :: VECTOR_DIV
VECTOR_DIV%X = VEC%X/SCALAR
VECTOR_DIV%Y = VEC%Y/SCALAR
END FUNCTION VECTOR_DIV
 
FUNCTION VECTOR_MULT(VEC, SCALAR)
TYPE(VECTOR), INTENT(IN) :: VEC
REAL, INTENT(IN) :: SCALAR
TYPE(VECTOR) :: VECTOR_MULT
VECTOR_MULT%X = VEC%X*SCALAR
VECTOR_MULT%Y = VEC%Y*SCALAR
END FUNCTION VECTOR_MULT
 
FUNCTION FROM_RTHETA(R, THETA)
REAL :: R, THETA
TYPE(VECTOR) :: FROM_RTHETA
FROM_RTHETA%X = R*SIN(THETA)
FROM_RTHETA%Y = R*COS(THETA)
END FUNCTION FROM_RTHETA
 
FUNCTION FROM_XY(X, Y)
REAL :: X, Y
TYPE(VECTOR) :: FROM_XY
FROM_XY%X = X
FROM_XY%Y = Y
END FUNCTION FROM_XY
 
FUNCTION PRETTY_PRINT(VEC)
TYPE(VECTOR), INTENT(IN) :: VEC
CHARACTER(LEN=100) PRETTY_PRINT
WRITE(PRETTY_PRINT,"(A, F0.5, A, F0.5, A)") "[", VEC%X, ", ", VEC%Y, "]"
END FUNCTION PRETTY_PRINT
END MODULE ROSETTA_VECTOR
 
PROGRAM VECTOR_DEMO
USE ROSETTA_VECTOR
IMPLICIT NONE
 
TYPE(VECTOR) :: VECTOR_1, VECTOR_2
REAL, PARAMETER :: PI = 4*ATAN(1.0)
REAL :: SCALAR
 
SCALAR = 2.0
 
VECTOR_1 = FROM_XY(2.0, 3.0)
VECTOR_2 = FROM_RTHETA(2.0, PI/6.0)
 
WRITE(*,*) "VECTOR_1 (X: 2.0, Y: 3.0) : ", PRETTY_PRINT(VECTOR_1)
WRITE(*,*) "VECTOR_2 (R: 2.0, THETA: PI/6) : ", PRETTY_PRINT(VECTOR_2)
WRITE(*,*) NEW_LINE('A')
WRITE(*,*) "VECTOR_1 + VECTOR_2 = ", PRETTY_PRINT(VECTOR_1+VECTOR_2)
WRITE(*,*) "VECTOR_1 - VECTOR_2 = ", PRETTY_PRINT(VECTOR_1-VECTOR_2)
WRITE(*,*) "VECTOR_1 / 2.0 = ", PRETTY_PRINT(VECTOR_1/SCALAR)
WRITE(*,*) "VECTOR_1 * 2.0 = ", PRETTY_PRINT(VECTOR_1*SCALAR)
END PROGRAM VECTOR_DEMO</syntaxhighlight>
{{out}}
<pre> VECTOR_1 (X: 2.0, Y: 3.0) : [2.00000, 3.00000]
VECTOR_2 (R: 2.0, THETA: PI/6) : [1.00000, 1.73205]
 
VECTOR_1 + VECTOR_2 = [3.00000, 4.73205]
VECTOR_1 - VECTOR_2 = [1.00000, 1.26795]
VECTOR_1 / 2.0 = [1.00000, 1.50000]
VECTOR_1 * 2.0 = [4.00000, 6.00000]
</pre>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Type Vector
Line 502 ⟶ 1,008:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 511 ⟶ 1,017:
[5, 7] / 2 = [2.5, 3.5]
</pre>
? "------------------------------------------------"
 
'compare with:
 
'----------------------------------------------------------------------------------------------------------------
 
dim shared as integer v01(2),v02(2),v03(2),v05(2)
 
dim shared as single v04(2)
 
'
sub v01_(x as integer,y as integer,z as integer):v01(0)=x:v01(1)=y:v01(2)=z:end sub
 
sub v02_(x as integer,y as integer,z as integer):v02(0)=x:v02(1)=y:v02(2)=z:end sub
 
sub v03_(x as integer,y as integer,z as integer):v03(0)=x:v03(1)=y:v03(2)=z:end sub
 
sub v04_(x as single,y as single,z as single):v04(0)=x:v04(1)=y:v04(2)=z:end sub
 
sub p(v() as integer):? "[";v(0);"/";v(1);"/";v(2);"]":end sub
 
sub ps(v() as single):? "[";v(0);"/";v(1);"/";v(2);"]":end sub
 
'
v01_(5,7,0):?"v01=";:p(v01())
 
v02_(2,3,0):?"v02=";:p(v02())
 
v03_(v01(0)+v02(0),v01(1)+v02(1),v01(2)+v02(2)) :?"v03=v01+v02=";:p(v03())
 
v03_(v01(0)-v02(0),v01(1)-v02(1),v01(2)-v02(2)) :?"v03=v01-v02=";:p(v03())
 
v03_(v01(0)*11,v01(1)*11,v01(2)*11) :?"v03=v01*11=" ;:p(v03()) '? integer
 
v04_(v01(0)/2,v01(1)/2,v01(2)/2) :?"v04=v01/2=" ;:ps(v04()) '? single
 
? "------------------------------------------------"
 
do:loop
 
'----------------------------------------------------------------------------------------------------------------
'
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 558 ⟶ 1,106:
fmt.Println(v1.scalarMul(11))
fmt.Println(v1.scalarDiv(2))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 572 ⟶ 1,120:
Solution:
 
<langsyntaxhighlight lang="groovy">import groovy.transform.EqualsAndHashCode
 
@EqualsAndHashCode
Line 603 ⟶ 1,151:
static Vector minus (Number a, Vector b) { -b + a }
static Vector multiply (Number a, Vector b) { b * a }
}</langsyntaxhighlight>
 
 
Test:
 
<langsyntaxhighlight lang="groovy">Number.metaClass.mixin VectorCategory
 
def a = [1, 5] as Vector
Line 623 ⟶ 1,171:
println "x * a == $x * $a == ${x*a}"
assert b / x == [3/4, -1/4] as Vector
println "b / x == $b / $x == ${b/x}"</langsyntaxhighlight>
 
Output:
Line 634 ⟶ 1,182:
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">
<lang Haskell>
add (u,v) (x,y) = (u+x,v+y)
minus (u,v) (x,y) = (u-x,v-y)
Line 650 ⟶ 1,198:
putStrLn $ "2 * vecB = " ++ (show.multByScalar 2 $ vecB)
putStrLn $ "vecA / 3 = " ++ (show.divByScalar vecA $ 3)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 665 ⟶ 1,213:
These are primitive (built in) operations in J:
 
<langsyntaxhighlight Jlang="j"> 5 7+2 3
7 10
5 7-2 3
Line 672 ⟶ 1,220:
55 77
5 7%2
2.5 3.5</langsyntaxhighlight>
 
A few things here might be worth noting:
Line 684 ⟶ 1,232:
It's perhaps also worth noting that J allows you to specify complex numbers using polar coordinates, and complex numbers can be converted to vectors using the special token (+.) - for example:
 
<langsyntaxhighlight Jlang="j"> 2ad45
1.41421j1.41421
+. 2ad45
Line 691 ⟶ 1,239:
1.41421j1.41421
+. 2ar0.785398
1.41421 1.41421</langsyntaxhighlight>
 
In the construction of these numeric constants, <code>ad</code> is followed by an '''a'''ngle in '''d'''egrees while <code>ar</code> is followed by an '''a'''ngle in '''r'''adians. This practice of embedding letters in a numeric constant is analogous to the use of '''e'''xponential notation when describing some floating point numbers.
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.util.Locale;
 
public class Test {
Line 736 ⟶ 1,284:
return String.format(Locale.US, "[%s, %s]", x, y);
}
}</langsyntaxhighlight>
 
<pre>[7.0, 10.0]
Line 750 ⟶ 1,298:
will work with conformal arrays of any dimension, and
sum/0 accepts any number of same-dimensional vectors.
<langsyntaxhighlight lang="jq">def polar(r; angle):
[ r*(angle|cos), r*(angle|sin) ];
 
Line 793 ⟶ 1,341:
def angle: atan2;
 
def topolar: [r, angle];</langsyntaxhighlight>
 
'''Examples'''
<langsyntaxhighlight lang="jq">def examples:
def pi: 1 | atan * 4;
 
Line 818 ⟶ 1,366:
"z2|topolar|polar is \($z2|topolar|polar2vector)" ;
 
examples</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -r -n -f vector.jq
v is [1,1]
w is [3,4]
Line 834 ⟶ 1,382:
z2 = polar(-2; pi/4) is [-1.4142135623730951,-1.414213562373095]
z2|topolar is [2,-2.356194490192345]
z2|topolar|polar is [-1.414213562373095,-1.4142135623730951]</langsyntaxhighlight>
 
=={{header|Julia}}==
Line 842 ⟶ 1,390:
 
'''The module''':
<langsyntaxhighlight lang="julia">module SpatialVectors
 
export SpatialVector
Line 889 ⟶ 1,437:
end
 
end # module Vectors</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
class Vector2D(val x: Double, val y: Double) {
Line 919 ⟶ 1,467:
println("11 * v2 = ${11.0 * v2}")
println("v1 / 2 = ${v1 / 2.0}")
}</langsyntaxhighlight>
 
{{out}}
Line 931 ⟶ 1,479:
11 * v2 = (22.0, 33.0)
v1 / 2 = (2.5, 3.5)
</pre>
 
=={{header|Lang}}==
<syntaxhighlight lang="lang">
struct &Vector {
$x
$y
}
 
fp.initVector = ($x, $y) -> {
return &Vector(fn.double($x), fn.double($y))
}
 
fp.addVector = ($a, $b) -> {
return parser.op(&Vector($a::$x + $b::$x, $a::$y + $b::$y))
}
 
fp.subVector = ($a, $b) -> {
return parser.op(&Vector($a::$x - $b::$x, $a::$y - $b::$y))
}
 
fp.mulVector = ($vec, $scalar) -> {
return parser.op(&Vector($vec::$x * $scalar, $vec::$y * $scalar))
}
 
fp.divVector = ($vec, $scalar) -> {
return parser.op(&Vector($vec::$x / $scalar, $vec::$y / $scalar))
}
 
fp.printVector = ($vec) -> {
fn.println([parser.op($vec::$x), parser.op($vec::$y)])
}
 
$vec1 = fp.initVector(5, 7)
$vec2 = fp.initVector(2, 3)
 
fp.printVector($vec1)
fp.printVector($vec2)
fn.println()
 
fp.printVector(fp.addVector($vec1, $vec2))
fp.printVector(fp.subVector($vec1, $vec2))
fp.printVector(fp.mulVector($vec1, 11))
fp.printVector(fp.divVector($vec1, 2))
</syntaxhighlight>
 
{{out}}
<pre>
[5.0, 7.0]
[2.0, 3.0]
 
[7.0, 10.0]
[3.0, 4.0]
[55.0, 77.0]
[2.5, 3.5]
</pre>
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">vector = {mt = {}}
 
function vector.new (x, y)
Line 966 ⟶ 1,569:
vector.print(a - b)
vector.print(a * 11)
vector.print(a / 2)</langsyntaxhighlight>
{{out}}
<pre>(7, 10)
Line 972 ⟶ 1,575:
(55, 77)
(2.5, 3.5)</pre>
 
=={{header|M2000 Interpreter}}==
Adapted from C
 
<syntaxhighlight lang="m2000 interpreter">
class vector {
private:
double x, y
public:
class literal {
double v
class:
module Literal(.v) {
}
}
operator "+" (b as vector){
.x+=b.x
.y+=b.y
}
operator "-" (b as vector){
.x-=b.x
.y-=b.y
}
operator "*" (b as literal){
.x*=b.v
.y*=b.v
}
operator "/" (b as literal){
.x/=b.v
.y/=b.v
}
property printVector {
value {
link parent x, y to x, y
value=format$(.fm$, str$(round(x,.r), .Lcid),if$(y>=0->"+", "-"),str$(abs(round(y,.r)),.lcid))
}
}="" // make type string
// added members to printVector (is a group type)
group printVector {
integer Lcid=1033
fm$="{0} î {1}{2} û"
r=6
}
class:
module vector(r as double, theta as double, Lcid=1033) {
def deg(rad)=rad*180@/pi
.printVector.Lcid<=Lcid
.x<=r*cos(deg(theta))
.y<=r*sin(deg(theta))
}
}
document s$
a=vector(3,pi/6)
s$="Vector a : "+a.printVector+{
}
b=vector(5,2*pi/3)
s$="Vector b : "+b.printVector+{
}
sum_a_b=a+b
s$="Sum of vectors a and b : "+sum_a_b.printVector+{
}
diff_a_b=a-b
s$="Difference of vectors a and b : "+diff_a_b.printVector+{
}
mul_a_3=a*a.literal(3)
s$="Multiplying vector a by 3 : "+mul_a_3.printVector+{
}
div_b_2.5=b/b.literal(2.5)
s$="Dividing vector b by 2.5 : "+div_b_2.5.printVector+{
}
report s$
clipboard s$
</syntaxhighlight>
{{out}}
<pre>
Vector a : 2.598076 î +1.5 û
Vector b : -2.5 î +4.330127 û
Sum of vectors a and b : 0.098076 î +5.830127 û
Difference of vectors a and b : 5.098076 î -2.830127 û
Multiplying vector a by 3 : 7.794229 î +4.5 û
Dividing vector b by 2.5 : -1 î +1.732051 û
</pre>
 
 
=={{header|Maple}}==
Vector class:<langsyntaxhighlight Maplelang="maple">module MyVector()
option object;
local value := Vector();
Line 1,001 ⟶ 1,687:
 
 
end module:</langsyntaxhighlight>
<langsyntaxhighlight Maplelang="maple">a := MyVector(<3|4>):
b := MyVector(<5|4>):
 
Line 1,008 ⟶ 1,694:
a - b;
a * 5;
a / 5;</langsyntaxhighlight>
{{out}}
<pre>
Line 1,017 ⟶ 1,703:
</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">ClearAll[vector,PrintVector]
vector[{r_,\[Theta]_}]:=vector@@AngleVector[{r,\[Theta]}]
vector[x_,y_]+vector[w_,z_]^:=vector[x+w,y+z]
a_ vector[x_,y_]^:=vector[a x,a y]
vector[x_,y_]-vector[w_,z_]^:=vector[x-w,y-z]
PrintVector[vector[x_,y_]]:=Print["vector has first component: ",x," And second component: ",y]
 
vector[1,2]+vector[3,4]
vector[1,2]-vector[3,4]
12vector[1,2]
vector[1,2]/3
PrintVector@vector[{Sqrt[2],45Degree}]</syntaxhighlight>
{{out}}
<pre>vector[4, 6]
vector[-2, -2]
vector[12, 24]
vector[1/3, 2/3]
SequenceForm["vector has first component: ", 1, " And second component: ", 1]</pre>
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">vplus = function(v1, v2)
return [v1[0]+v2[0],v1[1]+v2[1]]
end function
Line 1,042 ⟶ 1,746:
print vminus(vector2, vector1)
print vmult(vector1, 3)
print vdiv(vector2, 2)</langsyntaxhighlight>
{{out}}
<pre>
Line 1,052 ⟶ 1,756:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE Vector;
FROM FormatString IMPORT FormatString;
FROM RealStr IMPORT RealToStr;
Line 1,111 ⟶ 1,815:
 
ReadChar
END Vector.</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
{{trans|Java}}
<langsyntaxhighlight lang="nanoquery">class Vector
declare x
declare y
Line 1,148 ⟶ 1,852:
println new(Vector, 5, 7) - new(Vector, 2, 3)
println new(Vector, 5, 7) * 11
println new(Vector, 5, 7) / 2</langsyntaxhighlight>
{{out}}
<pre>[7.0, 10.0]
Line 1,154 ⟶ 1,858:
[55.0, 77.0]
[2.5, 3.5]</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import strformat
 
type Vec2[T: SomeNumber] = tuple[x, y: T]
 
proc initVec2[T](x, y: T): Vec2[T] = (x, y)
 
func`+`[T](a, b: Vec2[T]): Vec2[T] = (a.x + b.x, a.y + b.y)
 
func `-`[T](a, b: Vec2[T]): Vec2[T] = (a.x - b.x, a.y - b.y)
 
func `*`[T](a: Vec2[T]; m: T): Vec2[T] = (a.x * m, a.y * m)
 
func `/`[T](a: Vec2[T]; d: T): Vec2[T] =
if d == 0:
raise newException(DivByZeroDefect, "division of vector by 0")
when T is SomeInteger:
(a.x div d, a.y div d)
else:
(a.x / d, a.y / d)
 
func `$`[T](a: Vec2[T]): string =
&"({a.x}, {a.y})"
 
# Three ways to initialize a vector.
let v1 = initVec2(2, 3)
let v2: Vec2[int] = (-1, 2)
let v3 = (x: 4, y: -2)
 
echo &"{v1} + {v2} = {v1 + v2}"
echo &"{v3} - {v2} = {v3 - v2}"
 
# Float vectors.
let v4 = initVec2(2.0, 3.0)
let v5 = (x: 3.0, y: 2.0)
 
echo &"{v4} * 2 = {v4 * 2}"
echo &"{v3} / 2 = {v3 / 2}" # Int division.
echo &"{v5} / 2 = {v5 / 2}" # Float division.</syntaxhighlight>
 
{{out}}
<pre>(2, 3) + (-1, 2) = (1, 5)
(4, -2) - (-1, 2) = (5, -4)
(2.0, 3.0) * 2 = (4.0, 6.0)
(4, -2) / 2 = (2, -1)
(3.0, 2.0) / 2 = (1.5, 1.0)</pre>
 
=={{header|Oberon-2}}==
{{trans|Modula-2}}
<syntaxhighlight lang="oberon2">MODULE Vector;
 
IMPORT Out;
TYPE
Vector = POINTER TO VectorDesc;
VectorDesc = RECORD
x,y:REAL;
END;
 
VAR
a,b:Vector;
PROCEDURE Add*(a,b:Vector):Vector;
VAR res:Vector;
BEGIN
NEW(res);
res.x := a.x+b.x;
res.y := a.y+b.y;
RETURN res;
END Add;
 
PROCEDURE Sub*(a,b:Vector):Vector;
VAR res:Vector;
BEGIN
NEW(res);
res.x := a.x-b.x;
res.y := a.y-b.y;
RETURN res;
END Sub;
 
PROCEDURE Mul*(v:Vector;r:REAL):Vector;
VAR res:Vector;
BEGIN
NEW(res);
res.x := v.x*r;
res.y := v.y*r;
RETURN res;
END Mul;
 
PROCEDURE Div*(v:Vector;r:REAL):Vector;
VAR res:Vector;
BEGIN
NEW(res);
res.x := v.x/r;
res.y := v.y/r;
RETURN res;
END Div;
 
PROCEDURE Print*(op:ARRAY OF CHAR;v:Vector);
BEGIN
Out.String(op);
Out.String("(");
Out.Real(v.x,0);
Out.String(", ");
Out.Real(v.y,0);
Out.String(")");
END Print;
 
BEGIN
NEW(a); NEW(b);
a.x := 5.0; a.y := 7.0;
b.x := 2.0; b.y := 3.0;
Print("Add: ",Add(a,b));
Out.Ln;
Print("Sub: ",Sub(a,b));
Out.Ln;
Print("Mul: ",Mul(a,11.0));
Out.Ln;
Print("Div: ",Div(a,2.0));
Out.Ln
END Vector.
</syntaxhighlight>
 
{{out}}
<pre>Add: (7.0E+00, 1.0E+01)
Sub: (3.0E+00, 4.0E+00)
Mul: (5.5E+01, 7.7E+01)
Div: (2.5E+00, 3.5E+00)
</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">class Test {
function : Main(args : String[]) ~ Nil {
Vec2->New(5, 7)->Add(Vec2->New(2, 3))->ToString()->PrintLine();
Line 1,201 ⟶ 2,035:
return "[{$@x}, {$@y}]";
}
}</langsyntaxhighlight>
 
<pre>
Line 1,212 ⟶ 2,046:
=={{header|OCaml}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ocaml">module Vector =
struct
type t = { x : float; y : float }
Line 1,238 ⟶ 2,072:
printf "a-b: %s\n" Vector.(a - b |> to_string);
printf "a*11: %s\n" Vector.(a * 11. |> to_string);
printf "a/2: %s\n" Vector.(a / 2. |> to_string)</langsyntaxhighlight>
 
{{out}}
Line 1,253 ⟶ 2,087:
Ol has builtin vector type, but does not have built-in vector math.
The vectors can be created directly using function (vector 1 2 3) or from list using function (make-vector '(1 2 3)). Additionally, exists short forms of vector creation: #(1 2 3) and [1 2 3].
<langsyntaxhighlight lang="scheme">
(define :+ +)
(define (+ a b)
Line 1,261 ⟶ 2,095:
(error "error:" "not applicable (+ vector non-vector)"))
(if (vector? b)
(error "error:" "not applicable (+ non-vector vector)"))
(:+ a b))))
 
(define :- -)
Line 1,271 ⟶ 2,105:
(error "error:" "not applicable (+ vector non-vector)"))
(if (vector? b)
(error "error:" "not applicable (+ non-vector vector)"))
(:- a b))))
 
(define :* *)
Line 1,281 ⟶ 2,115:
(error "error:" "not applicable (* vector vector)"))
(if (vector? b)
(error "error:" "not applicable (* scalar vector)"))
(:* a b))))
 
(define :/ /)
Line 1,291 ⟶ 2,125:
(error "error:" "not applicable (/ vector vector)"))
(if (vector? b)
(error "error:" "not applicable (/ scalar vector)"))
(:/ a b))))
 
(define x [1 2 3 4 5])
Line 1,300 ⟶ 2,134:
(print x " * " 7 " = " (* x 7))
(print x " / " 7 " = " (/ x 7))
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,310 ⟶ 2,144:
 
=={{header|ooRexx}}==
<langsyntaxhighlight lang="oorexx">v=.vector~new(12,-3); Say "v=.vector~new(12,-3) =>" v~print
v~ab(1,1,6,4); Say "v~ab(1,1,6,4) =>" v~print
v~al(45,2); Say "v~al(45,2) =>" v~print
Line 1,367 ⟶ 2,201:
return '['self~x','self~y']'
 
::requires rxMath Library</langsyntaxhighlight>
{{out}}
<pre>v=.vector~new(12,-3) => [12,-3]
Line 1,379 ⟶ 2,213:
=={{header|Perl}}==
Typically we would use a module, such as [https://metacpan.org/pod/Math::Vector::Real Math::Vector::Real] or [https://metacpan.org/pod/Math::Complex Math::Complex]. Here is a very basic Moose class.
<langsyntaxhighlight lang="perl">packageuse Vectorv5.36;
 
package Vector;
use Moose;
use featureoverload 'say+'; => \&add,
'-' => \&sub,
 
use overload '+*' => \&addmul,
'-/' => \&subdiv,
'*' => \&mul,
'/' => \&div,
'""' => \&stringify;
 
Line 1,392 ⟶ 2,226:
has 'y' => (is =>'rw', isa => 'Num', required => 1);
 
sub add ($a, $b, $) { Vector->new( x => $a->x + $b->x, y => $a->y + $b->y) }
sub add {
sub sub ($a, $b, $) { Vector->new( x => $a->x - $b->x, y => $a->y - $b->y) }
my($a, $b) = @_;
sub mul ($a, $b, $) { Vector->new( x => $a->x +* $b->x, y => $a->y +* $b->y); }
sub div ($a, $b, $) { Vector->new( x => $a->x / $b, y => $a->y / $b) }
}
sub stringify ($self, $, $) { '(' . $self->x . ',' . $self->y . ')' }
sub sub {
my($a, $b) = @_;
Vector->new( x => $a->x - $b->x, y => $a->y - $b->y);
}
sub mul {
my($a, $b) = @_;
Vector->new( x => $a->x * $b, y => $a->y * $b);
}
sub div {
my($a, $b) = @_;
Vector->new( x => $a->x / $b, y => $a->y / $b);
}
sub stringify {
my $self = shift;
"(" . $self->x . "," . $self->y . ')';
}
 
package main;
Line 1,422 ⟶ 2,241:
say "a-b: ",$a-$b;
say "a*11: ",$a*11;
say "a/2: ",$a/2;</langsyntaxhighlight>
{{out}}
<pre>
Line 1,434 ⟶ 2,253:
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
Simply hold vectors in sequences, and there are builtin sequence operation routines:
<!--<syntaxhighlight lang="phix">-->
<lang Phix>constant a = {5,7}, b = {2, 3}
<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;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</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;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">}</span>
?sq_add(a,b)
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">sq_add</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>
?sq_sub(a,b)
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">sq_sub</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>
?sq_mul(a,11)
<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;">11</span><span style="color: #0000FF;">)</span>
?sq_div(a,2)</lang>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">sq_div</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre>
Line 1,449 ⟶ 2,271:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
def add + enddef
Line 1,478 ⟶ 2,300:
drop 2
getid mul opVect ?
getid div opVect ?</langsyntaxhighlight>
{{out}}
<pre>[7, 10]
Line 1,488 ⟶ 2,310:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de add (A B)
(mapcar + A B) )
(de sub (A B)
Line 1,500 ⟶ 2,322:
(println (sub X Y))
(println (mul X 11))
(println (div X 2)) )</langsyntaxhighlight>
{{out}}
<pre>
Line 1,511 ⟶ 2,333:
=={{header|PL/I}}==
{{trans|REXX}}
<langsyntaxhighlight lang="pli">*process source attributes xref or(!);
vectors: Proc Options(main);
Dcl (v,w,x,y,z) Dec Float(9) Complex;
Line 1,531 ⟶ 2,353:
Return(res);
End;
End;</langsyntaxhighlight>
{{out}}
<pre>[ 12.00000, -3.00000]
Line 1,545 ⟶ 2,367:
{{works with|PowerShell|2}}<br/>
A vector class is built in.
<langsyntaxhighlight PowerShelllang="powershell">$V1 = New-Object System.Windows.Vector ( 2.5, 3.4 )
$V2 = New-Object System.Windows.Vector ( -6, 2 )
$V1
Line 1,552 ⟶ 2,374:
$V1 - $V2
$V1 * 3
$V1 / 8</langsyntaxhighlight>
{{out}}
<pre> X Y Length LengthSquared
Line 1,566 ⟶ 2,388:
A vector class, PVector, is a Processing built-in. It expresses an x,y or x,y,z vector from the origin. A vector may return its components, magnitude, and heading, and also includes .add(), .sub(), .mult(), and .div() -- among other methods. Methods each have both a static form which returns a new PVector and an object method form which alters the original.
 
<langsyntaxhighlight lang="java">PVector v1 = new PVector(5, 7);
PVector v2 = new PVector(2, 3);
 
Line 1,581 ⟶ 2,403:
println(v1.add(v2));
println(v1.mult(10));
println(v1.div(10));</langsyntaxhighlight>
 
{{out}}
Line 1,603 ⟶ 2,425:
Python mode adds math operator overloading for Processing's PVector static methods.
 
<langsyntaxhighlight lang="python">v1 = PVector(5, 7)
v2 = PVector(2, 3)
 
Line 1,619 ⟶ 2,441:
println(v1.add(v2)) # v1 += v2; println(v2)
println(v1.mult(10)) # v1 *= 10; println(v1)
println(v1.div(10)) # v1 /= 10; println(v1)</langsyntaxhighlight>
 
=={{header|Python}}==
Line 1,625 ⟶ 2,447:
Implements a Vector Class that is initialized with origin, angular coefficient and value.
 
<langsyntaxhighlight lang="python">class Vector:
def __init__(self,m,value):
self.m = m
Line 1,693 ⟶ 2,515:
self.value.__round__(2),
self.x.__round__(2),
self.y.__round__(2))</langsyntaxhighlight>
 
Or Python 3.7 version using namedtuple and property caching:
<langsyntaxhighlight lang="python">from __future__ import annotations
import math
from functools import lru_cache
Line 1,771 ⟶ 2,593:
 
print("Division:")
print(v2 / 2)</langsyntaxhighlight>
{{Out}}
<pre>Pretty print:
Line 1,793 ⟶ 2,615:
 
We use <code>fl*</code> and <code>fl/</code> to try to get the most sensible result for vertical vectors.
<langsyntaxhighlight Racketlang="racket">#lang racket
 
(require racket/flonum)
Line 1,843 ⟶ 2,665:
(define (vec/e v l)
(vec (/ (vec-x v) l)
(/ (vec-y v) l)))</langsyntaxhighlight>
'''Tests
<langsyntaxhighlight Racketlang="racket">(vec/slope-norm 1 10)
 
(vec/slope-norm 0 10)
Line 1,857 ⟶ 2,679:
(vec+ (vec/slope-norm 1 10) (vec/slope-norm 1 2))
 
(vec*e (vec/slope-norm 4 5) 2)</langsyntaxhighlight>
 
{{out}}
Line 1,912 ⟶ 2,734:
(formerly Perl 6)
 
<syntaxhighlight lang="raku" perl6line>class Vector {
has Real $.x;
has Real $.y;
Line 1,959 ⟶ 2,781:
say -$u; #: vec[-3, -4]
say $u * 10; #: vec[30, 40]
say $u / 2; #: vec[1.5, 2]</langsyntaxhighlight>
 
=={{header|Red}}==
<langsyntaxhighlight lang="red">Red [
Source: https://github.com/vazub/rosetta-red
Tabs: 4
Line 1,984 ⟶ 2,806:
prin pad "v1 * 11" 10 print (copy v1) * 11
prin pad "v1 / 2" 10 print (copy v1) / 2
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,001 ⟶ 2,823:
 
The angular part of the vector (when defining) is assumed to be in degrees for this program.
<langsyntaxhighlight lang="rexx">/*REXX program shows how to support mathematical functions for vectors using functions. */
s1 = 11 /*define the s1 scalar: eleven */
s2 = 2 /*define the s2 scalar: two */
Line 2,041 ⟶ 2,863:
/*──────────────────────────────────────────────────────────────────────────────────────*/
.sinCos: parse arg z 1 _,i; q=x*x
do k=2 by 2 until p=z; p=z; _= -_*q / (k*(k+i)); z=z+_; end; return z</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 2,052 ⟶ 2,874:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Vector
 
Line 2,089 ⟶ 2,911:
see svect
see "]" + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,098 ⟶ 2,920:
</pre>
 
=={{header|RPL}}==
Basic vector (and matrix) handling is wired in RPL.
{{in}}
<pre>
[10,20,30] [1,2,3] +
[10,20,30] [1,2,3] -
[10,20,30] 5 *
[10,20,30] 5 /
</pre>
{{out}}
<pre>
4: [ 11 22 33 ]
3: [ 9 18 27 ]
2: [ 50 100 150 ]
1: [ 2 4 6 ]
</pre>
If the user wants to handle 2D vectors with possibility to use either polar or rectangular coordinates, vectors must be expressed as complex numbers, for which RPL provides <code>R→P</code> and <code>P→R</code> conversion instructions
(1,2) R→P
1: (2.2360679775,1.10714871779)
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class Vector
def self.polar(r, angle=0)
new(r*Math.cos(angle), r*Math.sin(angle))
Line 2,152 ⟶ 2,993:
p z.polar #=> [1.0, 1.5707963267948966]
p z = Vector.polar(-2, Math::PI/4) #=> Vector[-1.4142135623730951, -1.414213562373095]
p z.polar #=> [2.0, -2.356194490192345]</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight Rustlang="rust">use std::fmt;
use std::ops::{Add, Div, Mul, Sub};
 
Line 2,258 ⟶ 3,099:
println!("{:.4}", Vector::new(3.0, 4.2) / 2.3);
println!("{}", Vector::new(3, 4) / 2);
}</langsyntaxhighlight>
 
{{out}}
Line 2,272 ⟶ 3,113:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object Vector extends App {
 
case class Vector2D(x: Double, y: Double) {
Line 2,298 ⟶ 3,139:
 
println(s"\nSuccessfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">class MyVector(:args) {
 
has Number x
Line 2,352 ⟶ 3,193:
say -u #: vec[-3, -4]
say u*10 #: vec[30, 40]
say u/2 #: vec[1.5, 2]</langsyntaxhighlight>
 
=={{header|Swift}}==
 
{{trans|Rust}}
 
<syntaxhighlight lang="text">import Foundation
#if canImport(Numerics)
import Numerics
#endif
 
struct Vector<T: Numeric> {
var x: T
var y: T
 
func prettyPrinted(precision: Int = 4) -> String where T: CVarArg & FloatingPoint {
return String(format: "[%.\(precision)f, %.\(precision)f]", x, y)
}
 
static func +(lhs: Vector, rhs: Vector) -> Vector {
return Vector(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
 
static func -(lhs: Vector, rhs: Vector) -> Vector {
return Vector(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
 
static func *(lhs: Vector, scalar: T) -> Vector {
return Vector(x: lhs.x * scalar, y: lhs.y * scalar)
}
 
static func /(lhs: Vector, scalar: T) -> Vector where T: FloatingPoint {
return Vector(x: lhs.x / scalar, y: lhs.y / scalar)
}
 
static func /(lhs: Vector, scalar: T) -> Vector where T: BinaryInteger {
return Vector(x: lhs.x / scalar, y: lhs.y / scalar)
}
}
 
#if canImport(Numerics)
extension Vector where T: ElementaryFunctions {
static func fromPolar(radians: T, theta: T) -> Vector {
return Vector(x: radians * T.cos(theta), y: radians * T.sin(theta))
}
}
#else
extension Vector where T == Double {
static func fromPolar(radians: Double, theta: Double) -> Vector {
return Vector(x: radians * cos(theta), y: radians * sin(theta))
}
}
#endif
 
print(Vector(x: 4, y: 5))
print(Vector.fromPolar(radians: 3.0, theta: .pi / 3).prettyPrinted())
print((Vector(x: 2, y: 3) + Vector(x: 4, y: 6)))
print((Vector(x: 5.6, y: 1.3) - Vector(x: 4.2, y: 6.1)).prettyPrinted())
print((Vector(x: 3.0, y: 4.2) * 2.3).prettyPrinted())
print((Vector(x: 3.0, y: 4.2) / 2.3).prettyPrinted())
print(Vector(x: 3, y: 4) / 2)</syntaxhighlight>
 
{{out}}
 
<pre>Vector<Int>(x: 4, y: 5)
[1.5000, 2.5981]
Vector<Int>(x: 6, y: 9)
[1.4000, -4.8000]
[6.9000, 9.6600]
[1.3043, 1.8261]
Vector<Int>(x: 1, y: 2)</pre>
 
=={{header|Tcl}}==
Line 2,358 ⟶ 3,269:
Good artists steal .. code .. from the great RS on [http://wiki.tcl.tk/14022|the Tcl'ers wiki]. Seriously, this is a neat little procedure:
 
<langsyntaxhighlight Tcllang="tcl">namespace path ::tcl::mathop
proc vec {op a b} {
if {[llength $a] == 1 && [llength $b] == 1} {
Line 2,388 ⟶ 3,299:
check {vec * {5 7} 11} {55 77}
check {vec / {5 7} 2.0} {2.5 3.5}
check {polar 2 0.785398} {1.41421 1.41421}</langsyntaxhighlight>
 
The tests are taken from J's example:
Line 2,402 ⟶ 3,313:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Type vector
x As Double
y As Double
Line 2,448 ⟶ 3,359:
Debug.Print "scalar division : ";: display a: Debug.Print " /";: Debug.Print d;
Debug.Print "=";: display scalar_division(a, d)
End Sub</langsyntaxhighlight>{{out}}
<pre>addition : ( 2,500; 4,330)+( 1,000; -2,000)=( 3,500; 2,330)
subtraction : ( 2,500; 4,330)-( 1,000; -2,000)=( 1,500; 6,330)
Line 2,456 ⟶ 3,367:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Class Vector
Line 2,502 ⟶ 3,413:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>[7,10]
Line 2,511 ⟶ 3,422:
 
=={{header|WDTE}}==
<langsyntaxhighlight WDTElang="wdte">let a => import 'arrays';
let s => import 'stream';
 
Line 2,529 ⟶ 3,440:
 
let s* => smath *;
let s/ => smath /;</langsyntaxhighlight>
 
'''Example Usage:'''
 
<langsyntaxhighlight WDTElang="wdte">v+ [1; 2; 3] [2; 5; 2] -- io.writeln io.stdout;
s* 3 [1; 5; 10] -- io.writeln io.stdout;</langsyntaxhighlight>
 
{{out}}
Line 2,540 ⟶ 3,451:
<pre>[3; 7; 5]
[3; 15; 30]</pre>
 
=={{header|Wren}}==
<syntaxhighlight lang="wren">class Vector2D {
construct new(x, y) {
_x = x
_y = y
}
 
static fromPolar(r, theta) { new(r * theta.cos, r * theta.sin) }
 
x { _x }
y { _y }
 
+(v) { Vector2D.new(_x + v.x, _y + v.y) }
-(v) { Vector2D.new(_x - v.x, _y - v.y) }
*(s) { Vector2D.new(_x * s, _y * s) }
/(s) { Vector2D.new(_x / s, _y / s) }
 
toString { "(%(_x), %(_y))" }
}
 
var times = Fn.new { |d, v| v * d }
 
var v1 = Vector2D.new(5, 7)
var v2 = Vector2D.new(2, 3)
var v3 = Vector2D.fromPolar(2.sqrt, Num.pi / 4)
System.print("v1 = %(v1)")
System.print("v2 = %(v2)")
System.print("v3 = %(v3)")
System.print()
System.print("v1 + v2 = %(v1 + v2)")
System.print("v1 - v2 = %(v1 - v2)")
System.print("v1 * 11 = %(v1 * 11)")
System.print("11 * v2 = %(times.call(11, v2))")
System.print("v1 / 2 = %(v1 / 2)")</syntaxhighlight>
 
{{out}}
<pre>
v1 = (5, 7)
v2 = (2, 3)
v3 = (1, 1)
 
v1 + v2 = (7, 10)
v1 - v2 = (3, 4)
v1 * 11 = (55, 77)
11 * v2 = (22, 33)
v1 / 2 = (2.5, 3.5)
</pre>
 
{{libheader|Wren-vector}}
Alternatively, using the above module and producing exactly the same output as before:
<syntaxhighlight lang="wren">import "./vector" for Vector2
 
var v1 = Vector2.new(5, 7)
var v2 = Vector2.new(2, 3)
var v3 = Vector2.fromPolar(2.sqrt, Num.pi / 4)
System.print("v1 = %(v1)")
System.print("v2 = %(v2)")
System.print("v3 = %(v3)")
System.print()
System.print("v1 + v2 = %(v1 + v2)")
System.print("v1 - v2 = %(v1 - v2)")
System.print("v1 * 11 = %(v1 * 11)")
System.print("11 * v2 = %(Vector2.scale(11, v2))")
System.print("v1 / 2 = %(v1 / 2)")</syntaxhighlight>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">func real VAdd(A, B, C); \Add two 2D vectors
real A, B, C; \A:= B + C
[A(0):= B(0) + C(0); \VAdd(A, A, C) => A:= A + C
A(1):= B(1) + C(1);
return A;
];
 
func real VSub(A, B, C); \Subtract two 2D vectors
real A, B, C; \A:= B - C
[A(0):= B(0) - C(0); \VSub(A, A, C) => A:= A - C
A(1):= B(1) - C(1);
return A;
];
 
func real VMul(A, B, S); \Multiply 2D vector by a scalar
real A, B, S; \A:= B * S
[A(0):= B(0) * S; \VMul(A, A, S) => A:= A * S
A(1):= B(1) * S;
return A;
];
 
func real VDiv(A, B, S); \Divide 2D vector by a scalar
real A, B, S; \A:= B / S
[A(0):= B(0) / S; \VDiv(A, A, S) => A:= A / S
A(1):= B(1) / S;
return A;
];
 
proc VOut(Dev, A); \Output a 2D vector number to specified device
int Dev; real A; \e.g: Format(1,1); (-1.5, 0.3)
[ChOut(Dev, ^();
RlOut(Dev, A(0));
Text(Dev, ", ");
RlOut(Dev, A(1));
ChOut(Dev, ^));
];
 
proc Polar2Rect(@X, @Y, Ang, Dist); \Return rectangular coordinates
real X, Y, Ang, Dist;
[X(0):= Dist*Cos(Ang);
Y(0):= Dist*Sin(Ang);
]; \Polar2Rect
 
real V0(2), V1, V2, V3(2);
def Pi = 3.14159265358979323846;
[Format(1, 1);
V1:= [5., 7.];
V2:= [2., 3.];
Polar2Rect(@V3(0), @V3(1), Pi/4., sqrt(2.));
Text(0, "V1 = "); VOut(0, V1); CrLf(0);
Text(0, "V2 = "); VOut(0, V2); CrLf(0);
Text(0, "V3 = "); VOut(0, V3); CrLf(0);
CrLf(0);
Text(0, "V1 + V2 = "); VOut(0, VAdd(V0, V1, V2 )); CrLf(0);
Text(0, "V1 - V2 = "); VOut(0, VSub(V0, V1, V2 )); CrLf(0);
Text(0, "V1 * 11 = "); VOut(0, VMul(V0, V1, 11.)); CrLf(0);
Text(0, "11 * V2 = "); VOut(0, VMul(V0, V2, 11.)); CrLf(0);
Text(0, "V1 / 2 = "); VOut(0, VDiv(V0, V1, 2. )); CrLf(0);
]</syntaxhighlight>
 
{{out}}
<pre>
V1 = (5.0, 7.0)
V2 = (2.0, 3.0)
V3 = (1.0, 1.0)
 
V1 + V2 = (7.0, 10.0)
V1 - V2 = (3.0, 4.0)
V1 * 11 = (55.0, 77.0)
11 * V2 = (22.0, 33.0)
V1 / 2 = (2.5, 3.5)
</pre>
 
=={{header|Yabasic}}==
{{trans|Ring}}
<syntaxhighlight lang="yabasic">dim vect1(2)
vect1(1) = 5 : vect1(2) = 7
dim vect2(2)
vect2(1) = 2 : vect2(2) = 3
dim vect3(arraysize(vect1(),1))
 
for n = 1 to arraysize(vect1(),1)
vect3(n) = vect1(n) + vect2(n)
next n
print "[", vect1(1), ", ", vect1(2), "] + [", vect2(1), ", ", vect2(2), "] = ";
showarray(vect3)
 
for n = 1 to arraysize(vect1(),1)
vect3(n) = vect1(n) - vect2(n)
next n
print "[", vect1(1), ", ", vect1(2), "] - [", vect2(1), ", ", vect2(2), "] = ";
showarray(vect3)
 
for n = 1 to arraysize(vect1(),1)
vect3(n) = vect1(n) * 11
next n
print "[", vect1(1), ", ", vect1(2), "] * ", 11, " = ";
showarray(vect3)
 
for n = 1 to arraysize(vect1(),1)
vect3(n) = vect1(n) / 2
next n
print "[", vect1(1), ", ", vect1(2), "] / ", 2, " = ";
showarray(vect3)
end
 
sub showarray(vect3)
print "[";
svect$ = ""
for n = 1 to arraysize(vect3(),1)
svect$ = svect$ + str$(vect3(n)) + ", "
next n
svect$ = left$(svect$, len(svect$) - 2)
print svect$;
print "]"
end sub</syntaxhighlight>
{{out}}
<pre>[5, 7] + [2, 3] = [7, 10]
[5, 7] - [2, 3] = [3, 4]
[5, 7] * 11 = [55, 77]
[5, 7] / 2 = [2.5, 3.5]</pre>
 
=={{header|zkl}}==
This uses polar coordinates for everything (radians for storage, degrees for i/o), converting to (x,y) on demand. Math is done in place rather than generating a new vector. Using the builtin polar/rectangular conversions keeps the vectors normalized.
<langsyntaxhighlight lang="zkl">class Vector{
var length,angle; // polar coordinates, radians
fcn init(length,angle){ // angle in degrees
Line 2,575 ⟶ 3,674:
}
fcn toString{ "Vector(%f,%f\Ub0;)".fmt(length,angle.toDeg()) }
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">Vector(2,45).println();
Vector(2,45).print(" create");
(Vector(2,45) * 2).print(" *");
(Vector(4,90) / 2).print(" /");
(Vector(2,45) + Vector(2,45)).print(" +");
(Vector(4,45) - Vector(2,45)).print(" -");</langsyntaxhighlight>
{{out}}
<pre>
168

edits