Vector: Difference between revisions
m
syntax highlighting fixup automation
(Added XPL0 example.) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 20:
{{trans|D}}
<
Float x, y
Line 45:
print(Vector(5, 7) - Vector(2, 3))
print(Vector(5, 7) * 11)
print(Vector(5, 7) / 2)</
{{out}}
Line 57:
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<
DEFINE X_="+0"
Line 128:
PrintVec(v1) Print(" / ") PrintR(s)
Print(" = ") PrintVec(res)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Vector.png Screenshot from Atari 8-bit computer]
Line 142:
=={{header|ALGOL 68}}==
<
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>
{{out}}
<pre>
Line 169:
=={{header|BASIC256}}==
{{trans|Ring}}
<
dim vect1(2)
vect1[1] = 5 : vect1[2] = 7
Line 210:
print "[" & vect1[1] & ", " & vect1[2] & "] / " & 2 & " = ";
call showarray(vect3)
end</
{{out}}
<pre>[5, 7] + [2, 3] = [7, 10]
Line 221:
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.
<
⟨7 10⟩
5‿7 - 2‿3
Line 228:
⟨55 77⟩
5‿7 ÷ 2
⟨2.5 3.5⟩</
=={{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">
#include<stdio.h>
#include<math.h>
Line 316:
return 0;
}
</syntaxhighlight>
Output:
<pre>
Line 334:
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.Linq;
Line 389:
}
}
</syntaxhighlight>
{{out}}
<pre>[7,10]
Line 398:
=={{header|C++}}==
<
#include <cmath>
#include <cassert>
Line 465:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 472:
=={{header|CLU}}==
<
vector = cluster [T: type] is make, add, sub, mul, div,
get_x, get_y, to_string
Line 561:
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 </
{{out}}
<pre> a = (5.0000, 7.0000)
Line 571:
=={{header|D}}==
<
void main() {
Line 609:
sink.formattedWrite!"(%s, %s)"(x, y);
}
}</
{{out}}
Line 619:
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
program Vector;
Line 650:
.
</syntaxhighlight>
{{out}}
Line 661:
=={{header|F#|F sharp}}==
<
let add (ax, ay) (bx, by) =
Line 684:
printfn "%A" (mul a 11.0)
printfn "%A" (div a 2.0)
0 // return an integer exit code</
=={{header|Factor}}==
It should be noted the <code>math.vectors</code> vocabulary has words for treating any sequence like a vector. For instance:
<
(scratchpad) { 1 2 } { 3 4 } v+
--- Data stack:
{ 4 6 }</
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.
<
prettyprint.custom sequences ;
IN: rosetta-code.vector
Line 723:
M: vec pprint-delims drop \ VEC{ \ } ;
M: vec >pprint-sequence parts 2array ;
M: vec pprint* pprint-object ;</
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.
<
sequences ;
IN: rosetta-code.vector
Line 741:
! course.
5 2 <vec> 1.3 [ v* ] demo</
{{out}}
<pre>
Line 757:
{{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.
<
: v* swap over * >r * r> ;
: v/ swap over / >r / r> ;
: v+ >r swap >r + r> r> + ;
: v- >r swap >r - r> r> - ;</
{{out}}
Line 776:
=={{header|Fortran}}==
<
IMPLICIT NONE
Line 873:
WRITE(*,*) "VECTOR_1 / 2.0 = ", PRETTY_PRINT(VECTOR_1/SCALAR)
WRITE(*,*) "VECTOR_1 * 2.0 = ", PRETTY_PRINT(VECTOR_1*SCALAR)
END PROGRAM VECTOR_DEMO</
{{out}}
<pre> VECTOR_1 (X: 2.0, Y: 3.0) : [2.00000, 3.00000]
Line 886:
=={{header|FreeBASIC}}==
<
Type Vector
Line 922:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 933:
=={{header|Go}}==
<
import "fmt"
Line 978:
fmt.Println(v1.scalarMul(11))
fmt.Println(v1.scalarDiv(2))
}</
{{out}}
<pre>
Line 992:
Solution:
<
@EqualsAndHashCode
Line 1,023:
static Vector minus (Number a, Vector b) { -b + a }
static Vector multiply (Number a, Vector b) { b * a }
}</
Test:
<
def a = [1, 5] as Vector
Line 1,043:
println "x * a == $x * $a == ${x*a}"
assert b / x == [3/4, -1/4] as Vector
println "b / x == $b / $x == ${b/x}"</
Output:
Line 1,054:
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">
add (u,v) (x,y) = (u+x,v+y)
minus (u,v) (x,y) = (u-x,v-y)
Line 1,070:
putStrLn $ "2 * vecB = " ++ (show.multByScalar 2 $ vecB)
putStrLn $ "vecA / 3 = " ++ (show.divByScalar vecA $ 3)
</syntaxhighlight>
{{out}}
<pre>
Line 1,085:
These are primitive (built in) operations in J:
<
7 10
5 7-2 3
Line 1,092:
55 77
5 7%2
2.5 3.5</
A few things here might be worth noting:
Line 1,104:
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:
<
1.41421j1.41421
+. 2ad45
Line 1,111:
1.41421j1.41421
+. 2ar0.785398
1.41421 1.41421</
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}}==
<
public class Test {
Line 1,156:
return String.format(Locale.US, "[%s, %s]", x, y);
}
}</
<pre>[7.0, 10.0]
Line 1,170:
will work with conformal arrays of any dimension, and
sum/0 accepts any number of same-dimensional vectors.
<
[ r*(angle|cos), r*(angle|sin) ];
Line 1,213:
def angle: atan2;
def topolar: [r, angle];</
'''Examples'''
<
def pi: 1 | atan * 4;
Line 1,238:
"z2|topolar|polar is \($z2|topolar|polar2vector)" ;
examples</
{{out}}
<
v is [1,1]
w is [3,4]
Line 1,254:
z2 = polar(-2; pi/4) is [-1.4142135623730951,-1.414213562373095]
z2|topolar is [2,-2.356194490192345]
z2|topolar|polar is [-1.414213562373095,-1.4142135623730951]</
=={{header|Julia}}==
Line 1,262:
'''The module''':
<
export SpatialVector
Line 1,309:
end
end # module Vectors</
=={{header|Kotlin}}==
<
class Vector2D(val x: Double, val y: Double) {
Line 1,339:
println("11 * v2 = ${11.0 * v2}")
println("v1 / 2 = ${v1 / 2.0}")
}</
{{out}}
Line 1,354:
=={{header|Lua}}==
<
function vector.new (x, y)
Line 1,386:
vector.print(a - b)
vector.print(a * 11)
vector.print(a / 2)</
{{out}}
<pre>(7, 10)
Line 1,394:
=={{header|Maple}}==
Vector class:<
option object;
local value := Vector();
Line 1,421:
end module:</
<
b := MyVector(<5|4>):
Line 1,428:
a - b;
a * 5;
a / 5;</
{{out}}
<pre>
Line 1,438:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
vector[{r_,\[Theta]_}]:=vector@@AngleVector[{r,\[Theta]}]
vector[x_,y_]+vector[w_,z_]^:=vector[x+w,y+z]
Line 1,449:
12vector[1,2]
vector[1,2]/3
PrintVector@vector[{Sqrt[2],45Degree}]</
{{out}}
<pre>vector[4, 6]
Line 1,458:
=={{header|MiniScript}}==
<
return [v1[0]+v2[0],v1[1]+v2[1]]
end function
Line 1,480:
print vminus(vector2, vector1)
print vmult(vector1, 3)
print vdiv(vector2, 2)</
{{out}}
<pre>
Line 1,490:
=={{header|Modula-2}}==
<
FROM FormatString IMPORT FormatString;
FROM RealStr IMPORT RealToStr;
Line 1,549:
ReadChar
END Vector.</
=={{header|Nanoquery}}==
{{trans|Java}}
<
declare x
declare y
Line 1,586:
println new(Vector, 5, 7) - new(Vector, 2, 3)
println new(Vector, 5, 7) * 11
println new(Vector, 5, 7) / 2</
{{out}}
<pre>[7.0, 10.0]
Line 1,594:
=={{header|Nim}}==
<
type Vec2[T: SomeNumber] = tuple[x, y: T]
Line 1,631:
echo &"{v4} * 2 = {v4 * 2}"
echo &"{v3} / 2 = {v3 / 2}" # Int division.
echo &"{v5} / 2 = {v5 / 2}" # Float division.</
{{out}}
Line 1,641:
=={{header|Objeck}}==
<
function : Main(args : String[]) ~ Nil {
Vec2->New(5, 7)->Add(Vec2->New(2, 3))->ToString()->PrintLine();
Line 1,686:
return "[{$@x}, {$@y}]";
}
}</
<pre>
Line 1,697:
=={{header|OCaml}}==
{{trans|Perl}}
<
struct
type t = { x : float; y : float }
Line 1,723:
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)</
{{out}}
Line 1,738:
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].
<
(define :+ +)
(define (+ a b)
Line 1,785:
(print x " * " 7 " = " (* x 7))
(print x " / " 7 " = " (/ x 7))
</syntaxhighlight>
{{Out}}
<pre>
Line 1,795:
=={{header|ooRexx}}==
<
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:
return '['self~x','self~y']'
::requires rxMath Library</
{{out}}
<pre>v=.vector~new(12,-3) => [12,-3]
Line 1,864:
=={{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.
<
use Moose;
use feature 'say';
Line 1,907:
say "a-b: ",$a-$b;
say "a*11: ",$a*11;
say "a/2: ",$a/2;</
{{out}}
<pre>
Line 1,921:
{{libheader|Phix/basics}}
Simply hold vectors in sequences, and there are builtin sequence operation routines:
<!--<
<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:
<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>
<!--</
{{Out}}
<pre>
Line 1,937:
=={{header|Phixmonti}}==
<
def add + enddef
Line 1,966:
drop 2
getid mul opVect ?
getid div opVect ?</
{{out}}
<pre>[7, 10]
Line 1,976:
=={{header|PicoLisp}}==
<
(mapcar + A B) )
(de sub (A B)
Line 1,988:
(println (sub X Y))
(println (mul X 11))
(println (div X 2)) )</
{{out}}
<pre>
Line 1,999:
=={{header|PL/I}}==
{{trans|REXX}}
<
vectors: Proc Options(main);
Dcl (v,w,x,y,z) Dec Float(9) Complex;
Line 2,019:
Return(res);
End;
End;</
{{out}}
<pre>[ 12.00000, -3.00000]
Line 2,033:
{{works with|PowerShell|2}}<br/>
A vector class is built in.
<
$V2 = New-Object System.Windows.Vector ( -6, 2 )
$V1
Line 2,040:
$V1 - $V2
$V1 * 3
$V1 / 8</
{{out}}
<pre> X Y Length LengthSquared
Line 2,054:
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.
<
PVector v2 = new PVector(2, 3);
Line 2,069:
println(v1.add(v2));
println(v1.mult(10));
println(v1.div(10));</
{{out}}
Line 2,091:
Python mode adds math operator overloading for Processing's PVector static methods.
<
v2 = PVector(2, 3)
Line 2,107:
println(v1.add(v2)) # v1 += v2; println(v2)
println(v1.mult(10)) # v1 *= 10; println(v1)
println(v1.div(10)) # v1 /= 10; println(v1)</
=={{header|Python}}==
Line 2,113:
Implements a Vector Class that is initialized with origin, angular coefficient and value.
<
def __init__(self,m,value):
self.m = m
Line 2,181:
self.value.__round__(2),
self.x.__round__(2),
self.y.__round__(2))</
Or Python 3.7 version using namedtuple and property caching:
<
import math
from functools import lru_cache
Line 2,259:
print("Division:")
print(v2 / 2)</
{{Out}}
<pre>Pretty print:
Line 2,281:
We use <code>fl*</code> and <code>fl/</code> to try to get the most sensible result for vertical vectors.
<
(require racket/flonum)
Line 2,331:
(define (vec/e v l)
(vec (/ (vec-x v) l)
(/ (vec-y v) l)))</
'''Tests
<
(vec/slope-norm 0 10)
Line 2,345:
(vec+ (vec/slope-norm 1 10) (vec/slope-norm 1 2))
(vec*e (vec/slope-norm 4 5) 2)</
{{out}}
Line 2,400:
(formerly Perl 6)
<syntaxhighlight lang="raku"
has Real $.x;
has Real $.y;
Line 2,447:
say -$u; #: vec[-3, -4]
say $u * 10; #: vec[30, 40]
say $u / 2; #: vec[1.5, 2]</
=={{header|Red}}==
<
Source: https://github.com/vazub/rosetta-red
Tabs: 4
Line 2,472:
prin pad "v1 * 11" 10 print (copy v1) * 11
prin pad "v1 / 2" 10 print (copy v1) / 2
</syntaxhighlight>
{{out}}
<pre>
Line 2,489:
The angular part of the vector (when defining) is assumed to be in degrees for this program.
<
s1 = 11 /*define the s1 scalar: eleven */
s2 = 2 /*define the s2 scalar: two */
Line 2,529:
/*──────────────────────────────────────────────────────────────────────────────────────*/
.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</
{{out|output|text= when using the default inputs:}}
<pre>
Line 2,540:
=={{header|Ring}}==
<
# Project : Vector
Line 2,577:
see svect
see "]" + nl
</syntaxhighlight>
Output:
<pre>
Line 2,587:
=={{header|Ruby}}==
<
def self.polar(r, angle=0)
new(r*Math.cos(angle), r*Math.sin(angle))
Line 2,640:
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]</
=={{header|Rust}}==
<
use std::ops::{Add, Div, Mul, Sub};
Line 2,746:
println!("{:.4}", Vector::new(3.0, 4.2) / 2.3);
println!("{}", Vector::new(3, 4) / 2);
}</
{{out}}
Line 2,760:
=={{header|Scala}}==
<
case class Vector2D(x: Double, y: Double) {
Line 2,786:
println(s"\nSuccessfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")
}</
=={{header|Sidef}}==
{{trans|Raku}}
<
has Number x
Line 2,840:
say -u #: vec[-3, -4]
say u*10 #: vec[30, 40]
say u/2 #: vec[1.5, 2]</
=={{header|Swift}}==
Line 2,846:
{{trans|Rust}}
<syntaxhighlight lang="text">import Foundation
#if canImport(Numerics)
import Numerics
Line 2,900:
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)</
{{out}}
Line 2,916:
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:
<
proc vec {op a b} {
if {[llength $a] == 1 && [llength $b] == 1} {
Line 2,946:
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}</
The tests are taken from J's example:
Line 2,960:
=={{header|VBA}}==
<
x As Double
y As Double
Line 3,006:
Debug.Print "scalar division : ";: display a: Debug.Print " /";: Debug.Print d;
Debug.Print "=";: display scalar_division(a, d)
End Sub</
<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:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Class Vector
Line 3,060:
End Sub
End Module</
{{out}}
<pre>[7,10]
Line 3,069:
=={{header|WDTE}}==
<
let s => import 'stream';
Line 3,087:
let s* => smath *;
let s/ => smath /;</
'''Example Usage:'''
<
s* 3 [1; 5; 10] -- io.writeln io.stdout;</
{{out}}
Line 3,100:
=={{header|Wren}}==
<
construct new(x, y) {
_x = x
Line 3,132:
System.print("v1 * 11 = %(v1 * 11)")
System.print("11 * v2 = %(times.call(11, v2))")
System.print("v1 / 2 = %(v1 / 2)")</
{{out}}
Line 3,148:
=={{header|XPL0}}==
<
real A, B, C; \A:= B + C
[A(0):= B(0) + C(0); \VAdd(A, A, C) => A:= A + C
Line 3,206:
Text(0, "11 * V2 = "); VOut(0, VMul(V0, V2, 11.)); CrLf(0);
Text(0, "V1 / 2 = "); VOut(0, VDiv(V0, V1, 2. )); CrLf(0);
]</
{{out}}
Line 3,223:
=={{header|Yabasic}}==
{{trans|Ring}}
<
vect1(1) = 5 : vect1(2) = 7
dim vect2(2)
Line 3,263:
print svect$;
print "]"
end sub</
{{out}}
<pre>[5, 7] + [2, 3] = [7, 10]
Line 3,272:
=={{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.
<
var length,angle; // polar coordinates, radians
fcn init(length,angle){ // angle in degrees
Line 3,304:
}
fcn toString{ "Vector(%f,%f\Ub0;)".fmt(length,angle.toDeg()) }
}</
<
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(" -");</
{{out}}
<pre>
|