PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, September 16, 2022

[FIXED] How to mix f-string and LaTeX symbols in a print(...) statement?

 September 16, 2022     f-string, latex, printing, python     No comments   

Issue

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 $' + f' is {estimPi}')

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(...)?


Solution

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



Answered By - Marcin Cuprjak
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing