diff --git a/src/math/p5.Vector.js b/src/math/p5.Vector.js index 0b48490258..f97bea902f 100644 --- a/src/math/p5.Vector.js +++ b/src/math/p5.Vector.js @@ -3901,6 +3901,22 @@ p5.Vector = class { * @method clampToZero * @return {p5.Vector} with components very close to zero replaced with zero. * @chainable + * @example + *
+ * + * function setup() { + * // Create a 2D vector where the x-component is near-zero + * let v = createVector(0.00000000000000005, 5 ); + * + * console.log('Before:', v.x , v.y); + * + * // Clamp negligible value of x-component to zero + * v.clampToZero(); + * console.log('After:', v.x , v.y); + * describe('Round down very small numbers of vector components to zero'); + * } + * + *
*/ clampToZero() { this.x = this._clampToZero(this.x); diff --git a/test/unit/math/p5.Vector.js b/test/unit/math/p5.Vector.js index ef3570ee0b..85dc8d8034 100644 --- a/test/unit/math/p5.Vector.js +++ b/test/unit/math/p5.Vector.js @@ -1882,5 +1882,48 @@ suite('p5.Vector', function() { expect(p5.Vector.equals(a1, a2)).to.be.true; }); }); + + suite('p5.Vector.clampToZero()', function() { + let v; + + test('should clamp very small positive number of vector components to zero', function() { + v = new p5.Vector(0.0000000000000002, 5); + v.clampToZero(); + expect(v.x).to.equal(0); + expect(v.y).to.equal(5); + }); + + test('should clamp very small negative number of vector components to zero', function() { + v = new p5.Vector(-0.0000000000000002, 5); + v.clampToZero(); + expect(v.x).to.equal(0); + expect(v.y).to.equal(5); + }); + + test('should not clamp regular numbers of vector components', function() { + v = new p5.Vector(0.01, 5); + v.clampToZero(); + expect(v.x).to.equal(0.01); + expect(v.y).to.equal(5); + }); + + test('should leave zero components of a 2D vector unchanged', function() { + v = new p5.Vector(0, 0); + v.clampToZero(); + expect(v.x).to.equal(0); + expect(v.y).to.equal(0); + }); + + test('should clamp very small numbers in all components of a 3D vector to zero', function() { + v = new p5.Vector( + 0.00000000000000005, + -0.0000000000000002220446049250313, + 0.0000000000000002220446049250313); + v.clampToZero(); + expect(v.x).to.equal(0); + expect(v.y).to.equal(0); + expect(v.z).to.equal(0); + }); + }); }); });