python - 带有随机库和时间库的 Python 代码语法操作
问题描述
我正在使用python3.6+vscode编译一个程序,但是它显示错误,但我继续调试,没有改善。
希望能得到一些帮助!</p>
下面是代码:
from random import random
from time import perf_counter
DARTS = 1000*1000
hits = 0.0
start = perf_counter
for i in range(1,DARTS+1):
x, y = random(), random()
dist = pow(x ** 2 + y ** 2, 0.5)
if dist <= 1.0:
hits = hits + 1
pi = 4 * (hits/DARTS)
print("圆周率值是:{}".format(pi))
print("运行时间是:{:.5f}s".format(perf_counter()-start))
解决方案
如评论中所述,您的第 5 行应如下所示:
start = perf_counter()
在你的最后一行中,你从一个数字中减去一个函数:
print("运行时间是:{:.5f}s".format(perf_counter()-start))
正确的代码
from random import random
from time import perf_counter
DARTS = 1000*1000
hits = 0.0
start = perf_counter()
for i in range(1,DARTS+1):
x, y = random(), random()
dist = pow(x ** 2 + y ** 2, 0.5)
if dist <= 1.0:
hits = hits + 1
pi = 4 * (hits/DARTS)
print("圆周率值是:{}".format(pi))
print("运行时间是:{:.5f}s".format(perf_counter()-start))
你在尝试什么:
print("运行时间是:{:.5f}s".format(perf_counter()-perf_counter))
推荐阅读
- python - Django在url查询中需要参数
- hash - 我怎样才能找到这个哈希算法?
- java - 如何使用 jreactive-8583 从客户端向服务器发送 ISO8583 消息?
- date - Twig 中基于时间的切换
- python - 为什么我会收到此错误?google.protobuf.message.DecodeError:解析消息时出错
- elastic-stack - 如何使用 metricbeat 监控 filebeat 统计信息
- vue.js - 如何在 vuex nuxt 中获取嵌套的 getter
- java - 管道中的 Netty 消息
- javascript - SharePoint REST API
- java - 如何使 GML / JTS 几何在 Java 中有效?