Vector products: Difference between revisions

Add Swift
No edit summary
(Add Swift)
Line 4,004:
+--------+
end</lang>
 
=={{header|Swift}}==
 
<lang swift>import Foundation
 
infix operator • : MultiplicationPrecedence
infix operator × : MultiplicationPrecedence
 
public struct Vector {
public var x = 0.0
public var y = 0.0
public var z = 0.0
 
public init(x: Double, y: Double, z: Double) {
(self.x, self.y, self.z) = (x, y, z)
}
 
public static func • (lhs: Vector, rhs: Vector) -> Double {
return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z
}
 
public static func × (lhs: Vector, rhs: Vector) -> Vector {
return Vector(
x: lhs.y * rhs.z - lhs.z * rhs.y,
y: lhs.z * rhs.x - lhs.x * rhs.z,
z: lhs.x * rhs.y - lhs.y * rhs.x
)
}
}
 
let a = Vector(x: 3, y: 4, z: 5)
let b = Vector(x: 4, y: 3, z: 5)
let c = Vector(x: -5, y: -12, z: -13)
 
print("a: \(a)")
print("b: \(b)")
print("c: \(c)")
print()
print("a • b = \(a • b)")
print("a × b = \(a × b)")
print("a • (b × c) = \(a • (b × c))")
print("a × (b × c) = \(a × (b × c))")</lang>
 
{{out}}
 
<pre>a: Vector(x: 3.0, y: 4.0, z: 5.0)
b: Vector(x: 4.0, y: 3.0, z: 5.0)
c: Vector(x: -5.0, y: -12.0, z: -13.0)
 
a • b = 49.0
a × b = Vector(x: 5.0, y: 5.0, z: -7.0)
a • (b × c) = 6.0
a × (b × c) = Vector(x: -267.0, y: 204.0, z: -3.0)</pre>
 
=={{header|Tcl}}==