本文主要是介绍蒙特卡洛求PI(抛点法)TypeScript实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
解决node先console.log不能用
pnpm install -D tslib @types/node
tsconfig.json
{"compilerOptions": {"target": "es2020","module": "commonjs","lib": ["es2020"],"sourceMap": true,"outDir": "./dist","rootDir": "./src","strict": true,"moduleResolution": "node","baseUrl": "src","esModuleInterop": true,"experimentalDecorators": true,"emitDecoratorMetadata": true,"skipLibCheck": true,"forceConsistentCasingInFileNames": true},"include": ["src/**/*"],"exclude": ["dist", "node_modules"],"compileOnSave": false
}
Point
export class TPoint{x:number = 0;y:number = 0;constructor(x:number,y:number) {this.x = x;this.y = y;}getDistance(other:TPoint):number {let xDis = Math.abs(this.x - other.x);let yDis = Math.abs(this.y - other.y);return Math.sqrt(xDis*xDis + yDis*yDis);}
}// let tpoint:TPoint = new TPoint(1,1)
// let tpoint2:TPoint = new TPoint(3,3)
// console.log(tpoint.getDistance(tpoint2));
Circle
import { TPoint } from "./tspoint";class TCircle{radius: number = 0;point: TPoint;constructor(point: TPoint, radius: number) {this.radius = radius;this.point = point;}isInCircle(point: TPoint): boolean{let dis:number = this.point.getDistance(point)return dis <= this.radius;}
}let point:TPoint = new TPoint(1,1)
let circle:TCircle = new TCircle(point, 1);
// let point2 = new Point(2,2)
// console.log(circle.isInCircle(point2));
// let point3 = new Point(1.5, 1.5)
// console.log(circle.isInCircle(point3));
let total = 10000000;
let count = 0;
for(let i = 0; i < total; i++){let x = Math.random() * 2;let y = Math.random() * 2;let pointTmp:TPoint = new TPoint(x,y);if(circle.isInCircle(pointTmp)){count++;}
}console.log(count*4.0/total);
这篇关于蒙特卡洛求PI(抛点法)TypeScript实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!