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 MathSpectralNorm { 17 private static fnA(i: double, j: double): double { 18 return 1 / ((i + j) * (i + j + 1) / 2 + i + 1); 19 } 20 21 private static fnAu(u: double[], v: double[]): void { 22 for (let i: int = 0; i < v.length; i++) { 23 let t: double = 0; 24 for (let j: int = 0; j < u.length; j++) { 25 t += MathSpectralNorm.fnA(i, j) * u[j]; 26 } 27 v[i] = t; 28 } 29 } 30 31 private static fnAtu(u: double[], v: double[]): void { 32 for (let i: int = 0; i < v.length; i++) { 33 let t: double = 0; 34 for (let j: int = 0; j < u.length; j++) { 35 t += MathSpectralNorm.fnA(j, i) * u[j]; 36 } 37 v[i] = t; 38 } 39 } 40 41 private static fnAtAu(u: double[], v: double[], w: double[]): void { 42 MathSpectralNorm.fnAu(u, w); 43 MathSpectralNorm.fnAtu(w, v); 44 } 45 46 private static spectralnorm(n: int): double { 47 let i: int; 48 // Not parsed new double[n] 49 let u: double[] = new double[n]; 50 // Not parsed new double[n] 51 let w: double[] = new double[n]; 52 // Not parsed new double[n] 53 let v: double[] = new double[n]; 54 let vbv: double = 0; 55 let vv: double = 0; 56 57 for (i = 0; i < n; i++) { 58 u[i] = 1; 59 v[i] = w[i] = 0; 60 } 61 62 for (i = 0; i < 10; i++) { 63 MathSpectralNorm.fnAtAu(u, v, w); 64 MathSpectralNorm.fnAtAu(v, u, w); 65 } 66 67 for (i = 0; i < n; i++) { 68 vbv += u[i] * v[i]; 69 vv += v[i] * v[i]; 70 71 } 72 73 return sqrt(vbv / vv); 74 } 75 76 n1: int = 6; 77 n2: int = 48; 78 private static readonly expected: double = 5.086694231303284; 79 80 public run(): void { 81 let total: double = 0; 82 83 for (let i: int = this.n1; i <= this.n2; i *= 2) { 84 total += MathSpectralNorm.spectralnorm(i); 85 } 86 87 assert total == MathSpectralNorm.expected: "Incorrect result"; 88 } 89} 90 91function main(): void { 92 let a = new MathSpectralNorm; 93 a.run(); 94} 95