如何在 print(...) 语句中混合使用 f-string 和 LaTeX 符号?
How to mix f-string and LaTeX symbols in a print(...) statement?
我正在使用 Monte Carlo“四分之一圆”方法计算圆周率,使用以下程序:
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
有没有办法在 print(...)
中混合 f 字符串和 LaTeX 符号?
为什么不为此使用 unicode 符号?
print(f'with {n_points} draws, the estimated value of \u03C0 is {estimPi}')
输出:
抽取 10000 次,π 的估计值为 3.1164
我正在使用 Monte Carlo“四分之一圆”方法计算圆周率,使用以下程序:
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
有没有办法在 print(...)
中混合 f 字符串和 LaTeX 符号?
为什么不为此使用 unicode 符号?
print(f'with {n_points} draws, the estimated value of \u03C0 is {estimPi}')
输出: 抽取 10000 次,π 的估计值为 3.1164