javascript公式用于计算向量正常

问题描述 投票:0回答:2

提出以下问题并回答:

agiven 2分如何与两个点形成的线的直角绘制一条线?

,但是,我想在JavaScript函数中使用它,并想知道如何完成对向量归一化的步骤:

通过将每个组件除以向量的长度,给出了正常矢量的单位向量。 我没有矢量数学的经验,但是为了获得“ rno”向量,我必须将矢量的倒数乘以左或乘以左或右正常 - 我认为。 谁能帮助我了解如何实现这一目标? 我想我必须乘以所有组件,但是在漫长的一天结束时,数学教程看起来都像希腊语。

提前感谢。

每个向量由值定义,例如。 x和y。向量的长度由等式长度= SQRT(X^2+Y^2)给出。获得单位Vertor的操作称为归一化。正如您所写的那样,为了使向量归一化,我们将每个向量组件划分为长度。

lhye在JavaScript中实现的示例:

首先,您需要以某种方式定义向量。我们将创建名为Vector的新对象。然后,我们将添加一个计算长度和新x,y值的函数。

//creating Vector object var Vector = function(x,y) { this.x = x; this.y = y; } Vector.prototype.normalize = function() { var length = Math.sqrt(this.x*this.x+this.y*this.y); //calculating length this.x = this.x/length; //assigning new value to x (dividing x by length of the vector) this.y= this.y/length; //assigning new value to y } var v1 = new Vector(2,4) //creating new instance of Vector object v1 // Vector {x: 2, y: 4} v1.normalize() // normalizing our newly created instance v1 //Vector {x: 0.4472135954999579, y: 0.8944271909999159}
javascript math vector
2个回答
10
投票
注意,这只是许多可能的实现之一。

Edit: 您可以使用长度函数来表现出对象:

Vector.prototype.length = function() { return Math.sqrt(this.x*this.x+this.y*this.y) }

检查我们的V1矢量是否适当标准化:

v1.length();
//0.9999999999999999

使用类语法,以不同的方法将不同的步骤分开,并将向量视为不可变的媒介,您可以做到这一点:

class Vector {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        Object.freeze(this);
    }
    norm() {
        return (this.x**2 + this.y**2) ** .5;
    }
    scale(scalar) {
        return new Vector(scalar * this.x, scalar * this.y);
    }
    normalize() {
        return this.scale(1 / this.norm());
    }
}

const v = new Vector(2, 4);
console.log(v.normalize());

0
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.