45 lines
1.1 KiB
Python
45 lines
1.1 KiB
Python
from flask import Flask, jsonify, request
|
|
import time
|
|
from flask_cors import CORS
|
|
from decimal import Decimal, getcontext
|
|
|
|
app = Flask(__name__)
|
|
CORS(app)
|
|
|
|
def calculate_pi(n):
|
|
getcontext().prec = n * 14
|
|
pi = Decimal(0)
|
|
k = Decimal(0)
|
|
x = Decimal(1)
|
|
sixteen = Decimal(16)
|
|
|
|
for i in range(n):
|
|
pi += (Decimal(4) / (8*k + 1) -
|
|
Decimal(2) / (8*k + 4) -
|
|
Decimal(1) / (8*k + 5) -
|
|
Decimal(1) / (8*k + 6)) * x
|
|
k += 1
|
|
x /= 16
|
|
|
|
return pi
|
|
|
|
@app.route('/pi')
|
|
def get_pi():
|
|
try:
|
|
precision = int(request.args.get('precision', 10))
|
|
|
|
start_time = time.time()
|
|
pi = calculate_pi(precision)
|
|
duration = (time.time() - start_time)*1000
|
|
|
|
return jsonify({
|
|
'pi': f"{pi:.{precision}f}",
|
|
'time': f"{duration:.6f}ms",
|
|
'language': 'Python'
|
|
})
|
|
except ValueError:
|
|
return jsonify({'error': 'Invalid precision parameter'}), 400
|
|
|
|
if __name__ == '__main__':
|
|
print("Python server starting on port 8082...")
|
|
app.run(port=8082) |