// 随机数 0~10
function ran10() {
return Math.round(Math.random() * 10)
}
// 向量构造函数
function Vector(fun, row = 2) {
let arr = []
if (row > 3) {
return arr = null
}
for (let i = 0; i < row; i++) {
arr[i] = fun ? fun() : 0
}
return arr
}
// 向量的点乘
function vectorDotProduct(vector1, vector2) {
if (vector1.length !== vector2.length) return
let sum = 0
for (let i = 0; i < vector1.length; i++) {
sum += vector1[i] * vector2[i]
}
return sum
}
// 向量的大小
function vectorLength(vector) {
let sum = 0
let length = 0
for (let i = 0; i < vector.length; i++) {
sum += vector[i] * vector[i]
length = Math.pow(sum, 0.5)
}
return length
}
// 向量的夹角
function vectorAngle(vector1, vector2) {
let result = Math.acos(vectorDotProduct(vector1, vector2)
/ (vectorLength(vector1) * vectorLength(vector2))) * 180 / Math.PI
return result
// return Math.acos(vectorDotProduct(vector1, vector2)
// / (vectorLength(vector1) * vectorLength(vector2))) / 180 / Math.PI
}
// 向量的叉乘
function vectorCrossProduct() {
}
// 测试
let vector1 = new Vector(ran10,)
let vector2 = new Vector(ran10,)
console.log('vector1 = ', vector1)
console.log('vector2 = ', vector2)
console.log('vector1 · vector2 = ', vectorDotProduct(vector1, vector2))
console.log('|vector1| = ', vectorLength(vector1))
console.log('|vector2| = ', vectorLength(vector2))
console.log('θ = ', vectorAngle(vector1, vector2), '°'))
js向量
最新推荐文章于 2024-06-23 09:43:09 发布