如何将F-string和乳胶符号混合在打印(...)语句中?
我正在使用以下程序来计算使用Monte Carlo“四分之一圈”方法的PI
from random import random as rd
def estimPi(n_points):
counter = 0
for i in range(n_points):
x,y = rd(),rd()
if x**2 + y**2 < 1:
counter = counter + 1
estimPi = 4*(counter/n_points)
print(f'with {n_points} draws, the estimated value of pi is {estimPi}')
:
estimPi(10000)
给我(当然为例):
with 10000 draws, the estimated value of pi is 3.1304
我想修改print(...)行以打印文本中的pi符号,而不是字符串
“ pi”
。
我尝试过:
print(f'with {n_points} draws, the estimated value of ' + r'$ \pi $' + f' is {estimPi}')
但是这并不能给我我期望的东西:
with 10000 draws, the estimated value of $ \pi $ is 3.1276
有没有办法将f-strings和latex符号混合在print(...)
中?
I am calculating pi with the Monte Carlo "quarter circle" method, using the following program:
from random import random as rd
def estimPi(n_points):
counter = 0
for i in range(n_points):
x,y = rd(),rd()
if x**2 + y**2 < 1:
counter = counter + 1
estimPi = 4*(counter/n_points)
print(f'with {n_points} draws, the estimated value of pi is {estimPi}')
So that:
estimPi(10000)
gives me (as an example, of course):
with 10000 draws, the estimated value of pi is 3.1304
I would like to modify the print(...)
line in order to have the pi symbol in the text printed, instead of having the string "pi"
.
I tried:
print(f'with {n_points} draws, the estimated value of ' + r'$ \pi
but it doesn't give me what I expect:
with 10000 draws, the estimated value of $ \pi $ is 3.1276
Is there a way to mix f-strings and LaTeX symbols in a print(...)
?
+ f' is {estimPi}')
but it doesn't give me what I expect:
Is there a way to mix f-strings and LaTeX symbols in a print(...)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

为什么不为此使用Unicode符号?
输出:
使用10000次抽奖,π的估计值为3.1164
Why not use the unicode symbol for that?
output:
with 10000 draws, the estimated value of π is 3.1164