0

I am trying to write theta in a specific format to a .txt file. I present the current and expected output.

import numpy as np

theta = np.pi/3

with open('Contact angle.txt', 'w+') as f: 
    f.write(f"theta = {str(theta)}\n")

The current output is

theta = 1.0471975511965976

The expected output is

theta = pi/3
3
  • 3
    Is there a reason to not use f.write("theta = pi/3 \n") Commented Sep 7, 2022 at 16:36
  • Yes because I am changing theta and I want it to write automatically to the txt file in this format. Commented Sep 7, 2022 at 16:40
  • What should be the output if the code is changed to theta = 1.1? Commented Sep 7, 2022 at 17:02

4 Answers 4

3

NumPy doesn't understand symbolic math, so that's not going to work. What you should probably use instead is SymPy.

>>> import sympy
>>> theta = sympy.pi / 3
>>> theta
pi/3

And if you need to convert it to float, you can do that:

>>> float(theta)
1.0471975511965979
Sign up to request clarification or add additional context in comments.

Comments

1

Why not code it like this:

theta = "pi/3"
with open('Contact angle.txt', 'w+') as f: 
    f.write(f"theta = {theta}\n")

Comments

0

This might be a job that is best suited for SymPy.

If theta will always be pi/<integer>, then you could do something like

import numpy as np

theta = np.pi/3
divisor = int(np.pi/theta)

with open('Contact angle.txt', 'w+') as f: 
    f.write(f'theta = pi/{divisor}\n")

The code will have to get a lot more fancy if theta is always some fraction of pi: theta = <integer1>pi/<integer2>

1 Comment

FYI, I posted an answer using SymPy
0

you can write theta as a string and use the function eval to get the value of theta like this:

from numpy import pi

theta = "pi/3"

with open('Contact angle.txt', 'w+') as f: 
    f.write(f"theta = {theta}\n")

the output of eval(theta) will be 1.0471975511965976

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.