如何将F-string和乳胶符号混合在打印(...)语句中?

发布于 01-23 08:30 字数 974 浏览 3 评论 0原文

我正在使用以下程序来计算使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

慕烟庭风2025-01-30 08:30:30

为什么不为此使用Unicode符号?

    print(f'with {n_points} draws, the estimated value of \u03C0 is {estimPi}')

输出:
使用10000次抽奖,π的估计值为3.1164

Why not use the unicode symbol for that?

    print(f'with {n_points} draws, the estimated value of \u03C0 is {estimPi}')

output:
with 10000 draws, the estimated value of π is 3.1164

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文