1/* 2 * Copyright (c) 2022-2024 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 MathPartialSums { 17 static readonly n1: int = 1024; 18 static readonly n2: int = 16384; 19 static readonly expected: double = 60.08994194659945; 20 static g_flag: int = 0; 21 22 private static partial(n: int): double { 23 let a1: double = 0.0; 24 let a2: double = 0.0; 25 let a3: double = 0.0; 26 let a4: double = 0.0; 27 let a5: double = 0.0; 28 let a6: double = 0.0; 29 let a7: double = 0.0; 30 let a8: double = 0.0; 31 let a9: double = 0.0; 32 33 let twothirds: double = 2.0 / 3.0; 34 let alt: double = -1.0; 35 let k2: double = 0.0; 36 let k3: double = 0.0; 37 let sk: double = 0.0; 38 let ck: double = 0.0; 39 let res: double = 0.0; 40 41 for (let k: long = 1; k <= n; k++) { 42 k2 = k * k; 43 k3 = k2 * k; 44 sk = sin(k); 45 ck = cos(k); 46 alt = -alt; 47 48 a1 += power(twothirds, k - 1); 49 a2 += power(k, -0.5); 50 a3 += 1.0 / (k * k + 1.0); 51 a4 += 1.0 / (k3 * sk * sk); 52 a5 += 1.0 / (k3 * ck * ck); 53 a6 += 1.0 / k; 54 a7 += 1.0 / k2; 55 a8 += alt / k; 56 a9 += alt / (2 * k - 1); 57 } 58 59 res = a1 + a2 + a3 + a4 + a5; 60 61 if (res > 0) { 62 MathPartialSums.g_flag = 1; 63 } else { 64 MathPartialSums.g_flag = 2; 65 } 66 67 // NOTE: We don't try to validate anything from pow(), sin() or cos() 68 // because those aren't well-specified in ECMAScript. 69 return a6 + a7 + a8 + a9; 70 } 71 72 public static run(): void { 73 let sum: double = 0; 74 for (let j: int = MathPartialSums.n1; j <= MathPartialSums.n2; j *= 2) { 75 sum += MathPartialSums.partial(j); 76 } 77 78 assert sum == MathPartialSums.expected: "Incorrect result" 79 assert MathPartialSums.g_flag == 1 || MathPartialSums.g_flag == 2: "Incorrect g_flag"; 80 } 81} 82 83function main(): void { 84 MathPartialSums.run(); 85} 86 87 88