-
Notifications
You must be signed in to change notification settings - Fork 3
Vector
Chung Leong edited this page Jun 2, 2024
·
6 revisions
A vector in Zig is a special kind of array compatible with SIMD instructions of modern CPUs.
It has a higher memory alignment requirement. For example, @Vector(4, f32)
aligns to 16-byte
boundary (128-bit), whereas [4]f32
only aligns to a 4-byte boundary (32-bit).
pub const Vector = @Vector(3, f32);
pub fn dot(v1: Vector, v2: Vector) f32 {
return @reduce(.Add, v1 * v2);
}
pub fn cross(v1: Vector, v2: Vector) Vector {
const p1 = @shuffle(f32, v1, undefined, @Vector(3, i32){ 1, 2, 0 }) * @shuffle(f32, v2, undefined, @Vector(3, i32){ 2, 0, 1 });
const p2 = @shuffle(f32, v1, undefined, @Vector(3, i32){ 2, 0, 1 }) * @shuffle(f32, v2, undefined, @Vector(3, i32){ 1, 2, 0 });
return p1 - p2;
}
import { Vector, cross, dot } from './vector-example-1.zig';
const v1 = new Vector([ 0.5, 1, 0 ]);
const v2 = new Vector([ 3, -4, 9 ]);
const p1 = dot(v1, v2);
console.log(`dot product = ${p1}`);
const p2 = cross(v1, v2);
console.log(`cross product = [ ${[ ...p2 ]} ]`);
dot product = -2.5
cross product = [ 9,-4.5,-5 ]
Zigar does not use proxy to implement the bracket operator for vectors. Each element has its own
getter/setter so access is fast. Vector objects do not have get()
and set()
.