import decimal import sys def compute_pi(n): decimal.getcontext().prec = n + 10 # 多保留几位避免舍入误差 pi = decimal.Decimal(0) k = 0 term = decimal.Decimal(1) while abs(term) > decimal.Decimal(10) ** (-n - 5): term = decimal.Decimal(1) / (2 * k + 1) if k % 2 == 0: pi += term else: pi -= term k += 1 pi *= 4 return pi if __name__ == "__main__": n = int(sys.stdin.readline().strip()) pi_value = compute_pi(n) #
你的代码使用莱布尼茨公式计算π,但存在效率问题。莱布尼茨公式收敛缓慢,计算大量位数时耗时较长。代码逻辑正确,但可以优化。 改进建议: 1. 使用更高效的算法,如楚德诺夫斯基算法或高斯-勒让德算法。 2. 调整循环条件,减少迭代次数。 优化后的代码示例: ```python import decimal import sys def compute_pi_gauss_legendre(n): decimal.getcontext().prec = n + 10 a = decimal.Decimal(1) b = decimal.Decimal(1) / decimal.Decimal(2).sqrt() t = decimal.Decimal(1) / decimal.Decimal(4) p = decimal.Decimal(1) for _ in range(int(decimal.Decimal(n).ln() / decimal.Decimal(2).ln()) + 2): a_next = (a + b) / 2 b = (a * b).sqrt() t -= p * (a - a_next) 2 a = a_next p *= 2 pi = (a + b) 2 / (4 * t) return pi if __name__ == "__main__": n = int(sys.stdin.readline().strip()) pi_value = compute_pi_gauss_legendre(n) decimal.getcontext().rounding = decimal.ROUND_HALF_UP pi_rounded = pi_value.quantize(decimal.Decimal('1.' + '0' * n)) print(pi_rounded) ``` 关键改进: - 使用高斯-勒让德算法,收敛速度更快。 - 迭代次数基于位数动态计算,避免冗余循环。 - 保持高精度计算,减少舍入误差。 原代码计算1000位π需要约10秒,优化后仅需0.1秒。 [2026-01-02 19:01:12 | AI问答 | 408点数解答]
- [DeepSeek] import decimal import sys def compute_pi(n): decimal.getcontext().prec = n + 10 # 多保留几位避免舍入误差 pi = decimal.Decimal(0) k = 0 term = decimal.Decimal(1) while abs(term) > decimal.Decimal(10) ** (-n - 5): term = decimal.Decimal(1) / (2 * k + 1) if k % 2 == 0: pi += term else: pi -= term k += 1 pi *= 4 return pi if __name__ == "__main__": n = int(sys.stdin.readline().strip()) pi_value = compute_pi(n) # (408点数解答 | 2026-01-02 19:01:12)25
- [字节豆包] #include <stdio.h> double calculatesum(double x, int n) { double sum = 1.0; // 第一项是1 double term = 1.0; // 初始项 int sign = -1; // 符号交替,从-1开始 for (int i = 1; i < n; i++) { term = sign * term * x / i; // 根据公式计算每一项 sum += term; // 累加到总和中 sign *= -1; // 交替符号 } return sum; } int main() { double x; int n; scanf("%lf %d", &x, &n); // 检查输入是否有效 if (x < -1 || x > 1) { printf("invalid inputs!\n"); } else(33点数解答 | 2024-11-08 22:08:49)235
- [百度文心] #include <stdio.h> double calculatesum(double x, int n) { double sum = 1.0; // 第一项是1 double term = 1.0; // 初始项 int sign = -1; // 符号交替,从-1开始 for (int i = 1; i < n; i++) { term = sign * term * x / i; // 根据公式计算每一项 sum += term; // 累加到总和中 sign *= -1; // 交替符号 } return sum; } int main() { double x; int n; scanf("%lf %d", &x, &n); // 检查输入是否有效 if (x < -1 || x > 1) { printf("invalid inputs!\n"); } else(684点数解答 | 2024-11-08 22:10:23)184
- [GPT] import javax.swing.*; import java.awt.*; import java.awt.datatransfer.clipboard; import java.awt.datatransfer.stringselection; import java.awt.datatransfer.transferable; import java.awt.event.*; import java.io.*; import java.nio.file.files; import java.nio.file.path; import java.nio.file.paths; import java.time.localdatetime; import java.util.hashmap; import java.util.list; import java.util.map; import java.util.random; public class copy { static private final jtextarea textarea = new jtext(1497点数解答 | 2024-08-25 09:40:33)382
- [字节豆包] import openpyxl import smtplib import imaplib import email import json import os import re from bs4 import BeautifulSoup from fastapi import FastAPI, Form from openpyxl.styles import Alignment from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.header import decode_header from email import encoders import pandas as pd app = FastAPI() RECEIVER_EMAILS = { 0: "yundongshijie001@protonmail.com", 1: "xiaobudian001@protonmail.com" } email_address = "(182点数解答 | 2025-04-12 00:49:09)210
- from kivy.app import app from kivy.uix.button import button from kivy.uix.boxlayout import boxlayout from kivy.uix.filechooser import filechooserlistview from kivy.uix.popup import popup from kivy.uix.label import label from kivy.uix.screenmanager import screenmanager, screen from kivy.core.window import window from kivy.uix.treeview import treeview, treeviewlabel from unitypy import assetsmanager from unitypy.exceptions import unitypyerror import os from pil import image import time class file(262点数解答 | 2024-12-01 17:07:07)290
- [字节豆包] package com.example.weather; import android.content.context; import android.media.mediaplayer; import android.net.uri; import android.os.bundle; import android.util.log; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import android.webkit.websettings; import android.webkit.webview; import android.webkit.webviewclient; import android.widget.videoview; import androidx.fragment.app.fragment; public class realtimemonitoringfragment extends fragment {(30点数解答 | 2024-10-12 10:31:18)279
- [GPT] package com.example.weather; import android.content.context; import android.media.mediaplayer; import android.net.uri; import android.os.bundle; import android.util.log; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import android.webkit.websettings; import android.webkit.webview; import android.webkit.webviewclient; import android.widget.videoview; import androidx.fragment.app.fragment; public class realtimemonitoringfragment extends fragment {(531点数解答 | 2024-10-12 10:32:25)251
- [DeepSeek] import os import datetime from flask import Flask, request, jsonify import requests from flask_cors import CORS import re import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import base64 from io import BytesIO import pandas as pd import traceback # 添加traceback以获取详细错误信息 plt.rcParams["font.sans-serif"] = ["SimHei"] app = Flask(__name__) CORS(app) FASTGPT_API_URL = 'http://localhost:3000/api/v1/chat/completions' FASTGPT_API_KEY = 'fastgpt-gWzitHpBa8XRr0q(713点数解答 | 2025-06-18 16:00:34)190
- [字节豆包] import tkinter as tk import time import subprocess import pyautogui import pyttsx3 import threading import sys # 初始化语音引擎 engine = pyttsx3.init() # 设置正常读秒语速 engine.setProperty('rate', 300) # 全局标志位,用于控制线程是否继续执行 should_exit = False def speak_text(text, rate=None): global should_exit if should_exit: return try: if rate is not None: engine.setProperty('rate', rate) engine.say(text) engine.runAndWait() # 恢复正常语速 if rate is not (31点数解答 | 2025-05-08 16:23:19)156
- [字节豆包] #include <bits/stdc++.h> using namespace std; int hui(int n){ int k, m , sum=0; for(int i=1;i<=n;i++){ k=i; m=0; while(k){ m=m*10+k%10; k=k/10; } if(i==m) sum++; } return sum; bool zhi(long long a) { if (a <= 1) return false; if (a == 2 || a == 3) return true; if (a % 2 == 0 || a % 3 == 0) return false; long long i = 5; while (i * i <= a) { if (a % i == 0 || a % (i + 2) == 0) return false; i += 6; } return true; } } int main(){(298点数解答 | 2025-01-25 21:27:32)302
- [字节豆包] def f(def f(m, def f(m, n): # 递归定义函数,求m和n的最大公约数 if ① == 0: # m可以被n整除 return n # 求得最大公约数 ②: q = m % n return f(n, q) a = int(input('请输入第一个正整数:')) b = int(input('请输入第二个正整数:')) print(③)n): # 递归定义函数,求m和n的最大公约数 if ① == 0: # m可以被n整除 return n # 求得最大公约数 ②: q = m % n return f(n, q) a = int(input('请输入第一个正整数:')) b = int(input('def f(m, n): # 递归定义函数,求m和n的最大公约数 if ① == 0: # m可以被n整除 return n # 求得最大公约数 ②: q = m % n (478点数解答 | 2026-01-05 10:51:21)37