Skip to content

Commit

Permalink
Implement the cross product function for JS and RS
Browse files Browse the repository at this point in the history
  • Loading branch information
dfellis committed Nov 23, 2024
1 parent 7d8ec1c commit 210f7d3
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
10 changes: 10 additions & 0 deletions alan_std.js
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,16 @@ export class Str {
}
}

export function cross(a, b) {
// Assuming they're all the same type
let type = a[0].constructor;
return [
new type(a[1].val * b[2].val - a[2].val * b[1].val),
new type(a[2].val * b[0].val - a[0].val * b[2].val),
new type(a[0].val * b[1].val - a[1].val * b[0].val),
];
}

export class GPU {
constructor(adapter, device, queue) {
this.adapter = adapter;
Expand Down
12 changes: 12 additions & 0 deletions alan_std.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -411,3 +411,15 @@ assert.equal(new alanStd.I64(1).ctz(), 0n, "ctzI64(1) = 0");
assert.equal(new alanStd.I64(2).ctz(), 1n, "ctzI64(2) = 1");
assert.equal(new alanStd.I64(3).ctz(), 0n, "ctzI64(3) = 0");
assert.equal(new alanStd.I64(-9_223_372_036_854_775_808n).ctz(), 63n, "ctzI64(-9_223_372_036_854_775_808n) = 63");

assert.deepEqual(alanStd.cross(
[new alanStd.F64(1), new alanStd.F64(0), new alanStd.F64(0)],
[new alanStd.F64(0), new alanStd.F64(1), new alanStd.F64(0)],
), [new alanStd.F64(0), new alanStd.F64(0), new alanStd.F64(1)],
"cross([1, 0, 0], [0, 1, 0]) = [0, 0, 1]");

assert.deepEqual(alanStd.cross(
[new alanStd.F64(0), new alanStd.F64(1), new alanStd.F64(0)],
[new alanStd.F64(1), new alanStd.F64(0), new alanStd.F64(0)],
), [new alanStd.F64(0), new alanStd.F64(0), new alanStd.F64(-1)],
"cross([0, 1, 0], [1, 0, 0]) = [0, 0, -1]");
14 changes: 14 additions & 0 deletions alan_std/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -690,6 +690,20 @@ pub fn productset<V: std::clone::Clone + std::hash::Hash + Eq>(
out
}

/// Vector-related functions

pub fn cross<V>(a: &[V; 3], b: &[V; 3]) -> [V; 3]
where
V: std::ops::Deref + std::ops::Mul<Output = V> + std::ops::Sub<Output = V>,
<V as Deref>::Target: std::ops::Mul<Output = V> + Sized + Copy + std::ops::Sub<Output = V>,
{
[
*a[1] * *b[2] - *a[2] * *b[1],
*a[2] * *b[0] - *a[0] * *b[2],
*a[0] * *b[1] - *a[1] * *b[0],
]
}

/// GPU-related functions and types

pub struct GPU {
Expand Down

0 comments on commit 210f7d3

Please sign in to comment.