Vector: Difference between revisions

10,081 bytes added ,  1 month ago
m
Update Lang example: Use new struct definition syntax
(Added XPL0 example.)
m (Update Lang example: Use new struct definition syntax)
 
(20 intermediate revisions by 11 users not shown)
Line 20:
{{trans|D}}
 
<langsyntaxhighlight lang="11l">T Vector
Float x, y
 
Line 45:
print(Vector(5, 7) - Vector(2, 3))
print(Vector(5, 7) * 11)
print(Vector(5, 7) / 2)</langsyntaxhighlight>
 
{{out}}
Line 57:
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<langsyntaxhighlight Actionlang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
 
DEFINE X_="+0"
Line 128:
PrintVec(v1) Print(" / ") PrintR(s)
Print(" = ") PrintVec(res)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Vector.png Screenshot from Atari 8-bit computer]
Line 142:
 
=={{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 158:
print( ( "a*11: ", TOSTRING ( a * 11 ), newline ) );
print( ( "a/2 : ", TOSTRING ( a / 2 ), newline ) )
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 167:
</pre>
 
=={{header|BASIC256Arturo}}==
<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}}
<langsyntaxhighlight lang="freebasic">arraybase 1
dim vect1(2)
vect1[1] = 5 : vect1[2] = 7
Line 210 ⟶ 257:
print "[" & vect1[1] & ", " & vect1[2] & "] / " & 2 & " = ";
call showarray(vect3)
end</langsyntaxhighlight>
{{out}}
<pre>[5, 7] + [2, 3] = [7, 10]
Line 216 ⟶ 263:
[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.
 
<langsyntaxhighlight lang="bqn"> 5‿7 + 2‿3
⟨7 10⟩
5‿7 - 2‿3
Line 228 ⟶ 274:
⟨55 77⟩
5‿7 ÷ 2
⟨2.5 3.5⟩</langsyntaxhighlight>
 
=={{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 316 ⟶ 362:
return 0;
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 334 ⟶ 380:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 389 ⟶ 435:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>[7,10]
Line 398 ⟶ 444:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <cmath>
#include <cassert>
Line 465 ⟶ 511:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 472 ⟶ 518:
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">% Parameterized vector class
vector = cluster [T: type] is make, add, sub, mul, div,
get_x, get_y, to_string
Line 561 ⟶ 607:
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 </langsyntaxhighlight>
{{out}}
<pre> a = (5.0000, 7.0000)
Line 571 ⟶ 617:
 
=={{header|D}}==
<langsyntaxhighlight Dlang="d">import std.stdio;
 
void main() {
Line 609 ⟶ 655:
sink.formattedWrite!"(%s, %s)"(x, y);
}
}</langsyntaxhighlight>
 
{{out}}
Line 619 ⟶ 665:
=={{header|Delphi}}==
 
<syntaxhighlight lang="delphi">
<lang Delphi>
program Vector;
 
Line 650 ⟶ 696:
 
.
</syntaxhighlight>
</lang>
 
{{out}}
Line 658 ⟶ 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 684 ⟶ 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 723 ⟶ 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 741 ⟶ 827:
! course.
 
5 2 <vec> 1.3 [ v* ] demo</langsyntaxhighlight>
{{out}}
<pre>
Line 757 ⟶ 843:
{{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.
<langsyntaxhighlight 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> - ;</langsyntaxhighlight>
 
{{out}}
Line 776 ⟶ 862:
 
=={{header|Fortran}}==
<langsyntaxhighlight FORTRANlang="fortran">MODULE ROSETTA_VECTOR
IMPLICIT NONE
 
Line 873 ⟶ 959:
WRITE(*,*) "VECTOR_1 / 2.0 = ", PRETTY_PRINT(VECTOR_1/SCALAR)
WRITE(*,*) "VECTOR_1 * 2.0 = ", PRETTY_PRINT(VECTOR_1*SCALAR)
END PROGRAM VECTOR_DEMO</langsyntaxhighlight>
{{out}}
<pre> VECTOR_1 (X: 2.0, Y: 3.0) : [2.00000, 3.00000]
Line 886 ⟶ 972:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Type Vector
Line 922 ⟶ 1,008:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 931 ⟶ 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 978 ⟶ 1,106:
fmt.Println(v1.scalarMul(11))
fmt.Println(v1.scalarDiv(2))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 992 ⟶ 1,120:
Solution:
 
<langsyntaxhighlight lang="groovy">import groovy.transform.EqualsAndHashCode
 
@EqualsAndHashCode
Line 1,023 ⟶ 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 1,043 ⟶ 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 1,054 ⟶ 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 1,070 ⟶ 1,198:
putStrLn $ "2 * vecB = " ++ (show.multByScalar 2 $ vecB)
putStrLn $ "vecA / 3 = " ++ (show.divByScalar vecA $ 3)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,085 ⟶ 1,213:
These are primitive (built in) operations in J:
 
<langsyntaxhighlight Jlang="j"> 5 7+2 3
7 10
5 7-2 3
Line 1,092 ⟶ 1,220:
55 77
5 7%2
2.5 3.5</langsyntaxhighlight>
 
A few things here might be worth noting:
Line 1,104 ⟶ 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 1,111 ⟶ 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 1,156 ⟶ 1,284:
return String.format(Locale.US, "[%s, %s]", x, y);
}
}</langsyntaxhighlight>
 
<pre>[7.0, 10.0]
Line 1,170 ⟶ 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 1,213 ⟶ 1,341:
def angle: atan2;
 
def topolar: [r, angle];</langsyntaxhighlight>
 
'''Examples'''
<langsyntaxhighlight lang="jq">def examples:
def pi: 1 | atan * 4;
 
Line 1,238 ⟶ 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 1,254 ⟶ 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 1,262 ⟶ 1,390:
 
'''The module''':
<langsyntaxhighlight lang="julia">module SpatialVectors
 
export SpatialVector
Line 1,309 ⟶ 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 1,339 ⟶ 1,467:
println("11 * v2 = ${11.0 * v2}")
println("v1 / 2 = ${v1 / 2.0}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,351 ⟶ 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 1,386 ⟶ 1,569:
vector.print(a - b)
vector.print(a * 11)
vector.print(a / 2)</langsyntaxhighlight>
{{out}}
<pre>(7, 10)
Line 1,392 ⟶ 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,421 ⟶ 1,687:
 
 
end module:</langsyntaxhighlight>
<langsyntaxhighlight Maplelang="maple">a := MyVector(<3|4>):
b := MyVector(<5|4>):
 
Line 1,428 ⟶ 1,694:
a - b;
a * 5;
a / 5;</langsyntaxhighlight>
{{out}}
<pre>
Line 1,438 ⟶ 1,704:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[vector,PrintVector]
vector[{r_,\[Theta]_}]:=vector@@AngleVector[{r,\[Theta]}]
vector[x_,y_]+vector[w_,z_]^:=vector[x+w,y+z]
Line 1,449 ⟶ 1,715:
12vector[1,2]
vector[1,2]/3
PrintVector@vector[{Sqrt[2],45Degree}]</langsyntaxhighlight>
{{out}}
<pre>vector[4, 6]
Line 1,458 ⟶ 1,724:
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">vplus = function(v1, v2)
return [v1[0]+v2[0],v1[1]+v2[1]]
end function
Line 1,480 ⟶ 1,746:
print vminus(vector2, vector1)
print vmult(vector1, 3)
print vdiv(vector2, 2)</langsyntaxhighlight>
{{out}}
<pre>
Line 1,490 ⟶ 1,756:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE Vector;
FROM FormatString IMPORT FormatString;
FROM RealStr IMPORT RealToStr;
Line 1,549 ⟶ 1,815:
 
ReadChar
END Vector.</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
{{trans|Java}}
<langsyntaxhighlight lang="nanoquery">class Vector
declare x
declare y
Line 1,586 ⟶ 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,594 ⟶ 1,860:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import strformat
 
type Vec2[T: SomeNumber] = tuple[x, y: T]
Line 1,631 ⟶ 1,897:
echo &"{v4} * 2 = {v4 * 2}"
echo &"{v3} / 2 = {v3 / 2}" # Int division.
echo &"{v5} / 2 = {v5 / 2}" # Float division.</langsyntaxhighlight>
 
{{out}}
Line 1,639 ⟶ 1,905:
(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,686 ⟶ 2,035:
return "[{$@x}, {$@y}]";
}
}</langsyntaxhighlight>
 
<pre>
Line 1,697 ⟶ 2,046:
=={{header|OCaml}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ocaml">module Vector =
struct
type t = { x : float; y : float }
Line 1,723 ⟶ 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,738 ⟶ 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,785 ⟶ 2,134:
(print x " * " 7 " = " (* x 7))
(print x " / " 7 " = " (/ x 7))
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,795 ⟶ 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,852 ⟶ 2,201:
return '['self~x','self~y']'
 
::requires rxMath Library</langsyntaxhighlight>
{{out}}
<pre>v=.vector~new(12,-3) => [12,-3]
Line 1,864 ⟶ 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,877 ⟶ 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,907 ⟶ 2,241:
say "a-b: ",$a-$b;
say "a*11: ",$a*11;
say "a/2: ",$a/2;</langsyntaxhighlight>
{{out}}
<pre>
Line 1,921 ⟶ 2,255:
{{libheader|Phix/basics}}
Simply hold vectors in sequences, and there are builtin sequence operation routines:
<!--<langsyntaxhighlight Phixlang="phix">-->
<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>
<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>
Line 1,927 ⟶ 2,261:
<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>
<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>
<!--</langsyntaxhighlight>-->
{{Out}}
<pre>
Line 1,937 ⟶ 2,271:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
def add + enddef
Line 1,966 ⟶ 2,300:
drop 2
getid mul opVect ?
getid div opVect ?</langsyntaxhighlight>
{{out}}
<pre>[7, 10]
Line 1,976 ⟶ 2,310:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de add (A B)
(mapcar + A B) )
(de sub (A B)
Line 1,988 ⟶ 2,322:
(println (sub X Y))
(println (mul X 11))
(println (div X 2)) )</langsyntaxhighlight>
{{out}}
<pre>
Line 1,999 ⟶ 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 2,019 ⟶ 2,353:
Return(res);
End;
End;</langsyntaxhighlight>
{{out}}
<pre>[ 12.00000, -3.00000]
Line 2,033 ⟶ 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 2,040 ⟶ 2,374:
$V1 - $V2
$V1 * 3
$V1 / 8</langsyntaxhighlight>
{{out}}
<pre> X Y Length LengthSquared
Line 2,054 ⟶ 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 2,069 ⟶ 2,403:
println(v1.add(v2));
println(v1.mult(10));
println(v1.div(10));</langsyntaxhighlight>
 
{{out}}
Line 2,091 ⟶ 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 2,107 ⟶ 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 2,113 ⟶ 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 2,181 ⟶ 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 2,259 ⟶ 2,593:
 
print("Division:")
print(v2 / 2)</langsyntaxhighlight>
{{Out}}
<pre>Pretty print:
Line 2,281 ⟶ 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 2,331 ⟶ 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 2,345 ⟶ 2,679:
(vec+ (vec/slope-norm 1 10) (vec/slope-norm 1 2))
 
(vec*e (vec/slope-norm 4 5) 2)</langsyntaxhighlight>
 
{{out}}
Line 2,400 ⟶ 2,734:
(formerly Perl 6)
 
<syntaxhighlight lang="raku" perl6line>class Vector {
has Real $.x;
has Real $.y;
Line 2,447 ⟶ 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 2,472 ⟶ 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,489 ⟶ 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,529 ⟶ 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,540 ⟶ 2,874:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Vector
 
Line 2,577 ⟶ 2,911:
see svect
see "]" + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,586 ⟶ 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,640 ⟶ 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,746 ⟶ 3,099:
println!("{:.4}", Vector::new(3.0, 4.2) / 2.3);
println!("{}", Vector::new(3, 4) / 2);
}</langsyntaxhighlight>
 
{{out}}
Line 2,760 ⟶ 3,113:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object Vector extends App {
 
case class Vector2D(x: Double, y: Double) {
Line 2,786 ⟶ 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,840 ⟶ 3,193:
say -u #: vec[-3, -4]
say u*10 #: vec[30, 40]
say u/2 #: vec[1.5, 2]</langsyntaxhighlight>
 
=={{header|Swift}}==
Line 2,846 ⟶ 3,199:
{{trans|Rust}}
 
<syntaxhighlight lang="text">import Foundation
#if canImport(Numerics)
import Numerics
Line 2,900 ⟶ 3,253:
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)</langsyntaxhighlight>
 
{{out}}
Line 2,916 ⟶ 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,946 ⟶ 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,960 ⟶ 3,313:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Type vector
x As Double
y As Double
Line 3,006 ⟶ 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 3,014 ⟶ 3,367:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Class Vector
Line 3,060 ⟶ 3,413:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>[7,10]
Line 3,069 ⟶ 3,422:
 
=={{header|WDTE}}==
<langsyntaxhighlight WDTElang="wdte">let a => import 'arrays';
let s => import 'stream';
 
Line 3,087 ⟶ 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 3,100 ⟶ 3,453:
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">class Vector2D {
construct new(x, y) {
_x = x
Line 3,132 ⟶ 3,485:
System.print("v1 * 11 = %(v1 * 11)")
System.print("11 * v2 = %(times.call(11, v2))")
System.print("v1 / 2 = %(v1 / 2)")</langsyntaxhighlight>
 
{{out}}
Line 3,146 ⟶ 3,499:
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}}==
<langsyntaxhighlight XPL0lang="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
Line 3,206 ⟶ 3,576:
Text(0, "11 * V2 = "); VOut(0, VMul(V0, V2, 11.)); CrLf(0);
Text(0, "V1 / 2 = "); VOut(0, VDiv(V0, V1, 2. )); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 3,223 ⟶ 3,593:
=={{header|Yabasic}}==
{{trans|Ring}}
<langsyntaxhighlight lang="yabasic">dim vect1(2)
vect1(1) = 5 : vect1(2) = 7
dim vect2(2)
Line 3,263 ⟶ 3,633:
print svect$;
print "]"
end sub</langsyntaxhighlight>
{{out}}
<pre>[5, 7] + [2, 3] = [7, 10]
Line 3,272 ⟶ 3,642:
=={{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 3,304 ⟶ 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