1/* 2 * Copyright (c) 2023 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 16class Body { 17 constructor(x, vx, mass) { 18 this.x = x; 19 this.vx = vx; 20 this.mass = mass; 21 } 22} 23 24function advance(bodies, dt) { 25 const sqrt = Math.sqrt; 26 const size = bodies.length; 27 28 for (let i = 0; i < size; i++) { 29 const bodyi = bodies[i]; 30 let vxi = bodyi.vx; 31 const xi = bodyi.x; 32 const massi = bodyi.mass; 33 34 for (let j = i + 1; j < size; j++) { 35 const bodyj = bodies[j]; 36 const dx = xi - bodyj.x; 37 38 const d2 = dx * dx; 39 const mag = dt / (d2 * sqrt(d2)); 40 const massiMag = massi * mag; 41 42 const massj = bodyj.mass; 43 const massjMag = massj * mag; 44 vxi -= dx * massjMag; 45 46 bodyj.vx += dx * massiMag; 47 } 48 bodyi.vx = vxi; 49 50 bodyi.x += dt * vxi; 51 } 52} 53 54const PI = Math.PI; 55const SOLAR_MASS = 4 * PI * PI; 56 57function sun() { 58 return new Body(0.0, 0.0, SOLAR_MASS); 59} 60 61function sun1() { 62 return new Body(1.2, 3.1, PI); 63} 64 65const bodies = [sun(), sun1()]; 66const n = 100000; 67for (let i = 0; i < n; i++) { 68 advance(bodies, 0.01); 69} 70