1/* 2 * Copyright (c) 2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16export class MathUtil { 17 static readonly TWO = 2; 18 19 /** 20 * The internal calculation has only 6-bit accuracy, so if the two values are less than the threshold, 21 * they represent equality 22 */ 23 static readonly EQUALITY_THRESHOLD = 0.00001; 24 25 static distance(x1: number, y1: number, x2: number, y2: number): number { 26 let dstX = x1 - x2; 27 let dstY = y1 - y2; 28 return Math.sqrt(dstX * dstX + dstY * dstY); 29 } 30 31 static clamp(num: number, min: number, max: number): number { 32 return Math.min(Math.max(num, min), max); 33 } 34 35 /** 36 * Two numbers are equal 37 * @param lhs lhs 38 * @param rhs rhs 39 * @returns Are they equal 40 */ 41 static equals(lhs: number, rhs: number): boolean { 42 return Math.abs(lhs - rhs) < MathUtil.EQUALITY_THRESHOLD; 43 } 44 45 // Matrix multiplication, matrix column first; MxN * NxO => MxO 46 static multiple(mat1: number[], mat2: number[], m: number, n: number, o: number): Array<number> { 47 let result = new Array(m * o); // Result matrix, column first 48 for (let i = 0; i < m; i++) { // row 49 for (let j = 0; j < o; j++) { // column 50 /* 51 * [i, j]subscript = i + j * m 52 * => mat[i, j] = mat1 i Row * mat2 j Column = mat1(i,0)->(i,n-1) * mat2(0, j)->(n-1, j) 53 * = mat1[i + 0 * m] * mat2[j * m + 0] + ... + mat1[i + (n - 1) * m] * mat2[j * m + n - 1] 54 */ 55 let tmp = 0; 56 for (let k = 0; k < n; k++) { 57 tmp += mat1[i + k * m] * mat2[j * m + k]; 58 } 59 result[i + j * m] = tmp; 60 } 61 } 62 return result; 63 } 64}