I'm trying to change the output of an exponential string formatting. I've fitted a curve to some data and would like to write these into the plot. Problem is, the x e-y format doesn't look nice, is there a posibility to change it so x * 10^-y?
Here is an example of the code I'm working with:
plt.plot(x, y, 'x', label = '$f(t) = {a:.0f} \cdot x + {b:.2e}$'.format(a = para[0], b = para[1])
a is some number bigger than 10000, that's why there is no need for decimalnumbers, but b is around 10^-7. Writing it as a float is spacewasting for the leading 0s, but the e^-7 doesn't look nice for publishing, that why I would like to change the output of the e-formatter, so it gives \cdot 10^{-7} (the \cdot {} for LaTeX) back.
Thanks
I would suggest you write an ad-hoc function to format the number in the output you want, something like this:
import numpy as np
def myformat(x):
myexp = np.floor(np.log10(x))
xout = x*10**(-myexp)
strout = "{:.2f} \times 10^{}".format(xout, myexp)
return strout
All, that need to be formated in LaTex style, must be wrapped with $ sign:
label='$f(t)$ = $x$ $\cdot$10$^-$$^7$'
Sign ^ makes aftergoing char as superscript (x$^5$ will give x to the power of 5) and _ is using for subscript (x$_5$ will give you x with index 5)
Related
(Sorry for my english...)
I'm looking for a method to creat a plot.title which depends of my variables already defined at the begining.
I'm not asking you to make it for me. Just to help me to find documents, sites, forum or things like that. I haven't find in on Google and i don't know what to type coz english isn't my native language.
Currently, i'm showing a graph and creating a pdf. which also contain the graph, like that :
graphic = plt.figure(1)
plt.plot(ts, xs, label="Position")
plt.plot(ts, vs, label="Velocity")
plt.title("euler-k-10-c-0.1-dt-0.01")
plt.legend()
plt.xlabel("Time ts")
plt.ylabel("Valors of position xs and velocity vs")
plt.show()
pp = PdfPages("Graphics.pdf")
pp.savefig(graphic, dpi = 300, transparent = True)
pp.close()
What i want to, is to modify this line :
plt.title("euler-k-10-c-0.1-dt-0.01")
I'm supposed to enter the valors of k, c and dt variables, and i want to change the name of the graphic to make it concur with the valors choosen for these variables.
For example, my code ask to enter the valors of k, c and dt, so i enter :
k = 1 ; c = 0 ; dt = 0.1
Then the graph title is : euler-k-1-c-0-dt-0.1
Thank you very much !
The string entering the plot title can be composed of variables like any other string. In your particular case, something like
k = 1
c = 0
dt = 0.1
plt.title(f'euler-k-{k}-c-{c}-dt-{dt}')
would do the job.
Here we've used formatted string literals; for other approaches to formatting a string, see e.g. this overview.
def make_plots(tx,xs,k,c,dt)
graphic = plt.figure(1)
plt.plot(ts, xs, label="Position")
plt.plot(ts, vs, label="Velocity")
plt.title(f'euler-k-{k}-c-{c}-dt-{dt}')
plt.legend()
plt.xlabel("Time ts")
plt.ylabel("Valors of position xs and velocity vs")
plt.show()
pp = PdfPages("Graphics.pdf")
pp.savefig(graphic, dpi = 300, transparent = True)
pp.close()
Make a function and call it as often as you change your k,c and dt.
Ow ! Thank you, i didn't think i was that easy.
Make a function and call it as often as you change your k,c and dt.
Hum.. Yes thank you ! But that's not the point haha.
this :
plt.title(f'euler-k-{k}-c-{c}-dt-{dt}')
answer my question. It works ! Now i can do that :
k = int(input("Enter the valor of k : "))
And the valor of k that i entered is considered in the title of my graph !
Thanks !
PS : I was also wondering why there was an error message when i wrote it :
k = input("Enter the valor of k : ")
It's because the "thing" you write when the input is executed, is considered as a string, and not an integer or a float ! So i have to add int() to make it works !
Thank you guys, you're awesome !
We are working on a big mathematical project with a lot of long equations and derivatives, which are produced by Wolfram Mathematica. We have more than 1000 very long equations.
Master program is written in Java and Mathematica is only used for generating equations. Our goal is to transform "Mathematica" form to "Java" form of equation. Then we can copy/paste generated code directly to "Java" code.
So for example we have short equation in Mathematica form:
Sqrt[((Cos[R]*X1 - X2)^2 + (Sin[R]*Y1 - Y2)^2)/S^2]/S
And we want to have it in Java form, so this is expected result:
Math.sqrt((Math.pow(Math.cos(R) * X1 - X2, 2) + Math.pow(Math.sin(R) * Y1 - Y2, 2)) / Math.pow(S, 2)) / S
Here is short python script, which manages some functions:
E = "Sqrt[((Cos[R]*X1 - X2)^2 + (Sin[R]*Y1 - Y2)^2)/S^2]/S"
E = E.replace("[", "(") # Replaces Square brackets with normal brackets
E = E.replace("]", ")") # Replaces Square brackets with normal brackets
E = E.replace("*", " * ") # Add some spaces for easier reading
E = E.replace("/", " / ") # Add some spaces for easier reading
E = E.replace("Cos", "Math.cos") # Change "Mathematica" cos to "Java" cos
E = E.replace("Sin", "Math.sin") # Change "Mathematica" sin to "Java" sin
E = E.replace("Sqrt", "Math.sqrt") # Change "Mathematica" SQRT to "Java" SQRT
# Converting Power function is missing here... This is a must :)
print(E)
Above code produces:
Math.sqrt(((Math.cos(R) * X1 - X2)^2 + (Math.sin(R) * Y1 - Y2)^2) / S^2) / S
The problem is that we didn't find any solution for power function. We wanted to use python regex, but we cannot find any proper solution. The problem is that power function has to take everything within brackets, so for example:
(Math.cos(R) * X1 - X2)^2 >>>> Math.pow(Math.cos(R) * X1 - X2, 2)
I hope that somebody has a quick and fancy solution. Otherwise I will need to take some time and write a long and "dirty" script, which will take care of this problem.
Thanks for your help :)
Your regex search could be somethig like this:
import re
E = "(Math.cos(R) * X1 - X2)^2"
regex = re.compile(r'\((.*)\)\^(\d)')
match = regex.match(E)
new_E = "Math.pow(%s, %s)" % (match.group(1), match.group(2))
print(new_E) # Math.pow(Math.cos(R) * X1 - X2, 2)
The way it works is by searching for anything inside parenthesis, followed by ^n, being n a digit from 0 to 9.
I hope you can adapt this to be as generalized as you need it to be.
I tried something using mathematica's fullform[] function which turns a^b into Power[a,b]. Then I changed the Power[a,b] to some arbitrary function e.g PowerJ[a,b] using find and replace. Then I could change back to input stlye to return the formula to a form with has "*,+" etc. I was then able to use your code above to change the PowerJ[a,b] to Math.pow[a,b].
I built a calculator for a bio equation, and I think I've narrowed down the source of my problem, which is a natural log I take:
goldman = ((R * T) / F) * cmath.log(float(top_row) / float(bot_row))
print("Membrane potential: " + str(goldman) + "V"
My problem is that it will only display the output in a complex form:
Membrane potential: (0.005100608207126714+0j)V
Is there any way of getting this to print as a floating number? Nothing I've tried has worked.
Complex numbers have a real part and an imaginary part:
>>> c = complex(1, 0)
>>> c
(1+0j)
>>> c.real
1.0
It looks like you just want the real part... so:
print("Membrane potential: " + str(goldman.real) + "V"
Use math.log instead of cmath.log.
Since you don't want the imaginary part of the result, it would be better to use math.log instead of cmath.log. This way, you'll get an error if your input is not in the valid domain for a real log, which is much better than silently giving you meaningless results (for example, if top_row is negative). Also, complex numbered results make no sense for this particular equation.
ie, use:
goldman = ((R * T) / F) * math.log(float(top_row) / float(bot_row))
If you want to just convert it to float value you can do this:
def print_float(x1):
a=x1.real
b=x1.imag
val=a+b
print(val)
ec=complex(2,3)
In this way you can actually get the floating value.
It is simple if you need only real part of the complex number.
goldman = 0.005100608207126714+0j
print(goldman)
(0.005100608207126714+0j)
goldman = float(goldman.real)
print(goldman)
0.005100608207126714
If you need absolute value then use following
goldman = 0.005100608207126714+0j
print(goldman)
(0.005100608207126714+0j)
goldman = float(abs(goldman))
print(goldman)
0.005100608207126714
print(type(goldman))
<class 'float'>
Say I have an expression which I would like to display in LateX form and one which is a result of an analytical calculation where variables like theta appear and are pretty printed in the end. I would like to print both in one line. Here an example:
from IPython.display import display, Math, Latex
import numpy as np
from sympy import *
init_printing()
# In[1]:
name='\Gamma^'+str(1)+'_{'+str(2)+str(3)+'}'+'='
# In[2]:
theta = symbols('theta')
# In[3]:
display(Math(name),theta)
The last command prints name in a pretty form (LateX) as well as theta. However, a line-break is added which I would like to omit. How can this be achieved?
You need to form latex string first. Use sympy.latex() to make string from any printable sympy variable:
display(Math(name + latex(theta)))
I also wrote simple function with variable number of arguments for such output. No need to wrap variables with latex() here:
def prlat(*args):
str = ''
for arg in args:
str += latex(arg)
display(Math(str))
prlat(name, theta, '= 0')
Python/Numpy Problem. Final year Physics undergrad... I have a small piece of code that creates an array (essentially an n×n matrix) from a formula. I reshape the array to a single column of values, create a string from that, format it to remove extraneous brackets etc, then output the result to a text file saved in the user's Documents directory, which is then used by another piece of software. The trouble is above a certain value for "n" the output gives me only the first and last three values, with "...," in between. I think that Python is automatically abridging the final result to save time and resources, but I need all those values in the final text file, regardless of how long it takes to process, and I can't for the life of me find how to stop it doing it. Relevant code copied beneath...
import numpy as np; import os.path ; import os
'''
Create a single column matrix in text format from Gaussian Eqn.
'''
save_path = os.path.join(os.path.expandvars("%userprofile%"),"Documents")
name_of_file = 'outputfile' #<---- change this as required.
completeName = os.path.join(save_path, name_of_file+".txt")
matsize = 32
def gaussf(x,y): #defining gaussian but can be any f(x,y)
pisig = 1/(np.sqrt(2*np.pi) * matsize) #first term
sumxy = (-(x**2 + y**2)) #sum of squares term
expden = (2 * (matsize/1.0)**2) # 2 sigma squared
expn = pisig * np.exp(sumxy/expden) # and put it all together
return expn
matrix = [[ gaussf(x,y) ]\
for x in range(-matsize/2, matsize/2)\
for y in range(-matsize/2, matsize/2)]
zmatrix = np.reshape(matrix, (matsize*matsize, 1))column
string2 = (str(zmatrix).replace('[','').replace(']','').replace(' ', ''))
zbfile = open(completeName, "w")
zbfile.write(string2)
zbfile.close()
print completeName
num_lines = sum(1 for line in open(completeName))
print num_lines
Any help would be greatly appreciated!
Generally you should iterate over the array/list if you just want to write the contents.
zmatrix = np.reshape(matrix, (matsize*matsize, 1))
with open(completeName, "w") as zbfile: # with closes your files automatically
for row in zmatrix:
zbfile.writelines(map(str, row))
zbfile.write("\n")
Output:
0.00970926751178
0.00985735189176
0.00999792646484
0.0101306077521
0.0102550302672
0.0103708481917
0.010477736974
0.010575394844
0.0106635442315
.........................
But using numpy we simply need to use tofile:
zmatrix = np.reshape(matrix, (matsize*matsize, 1))
# pass sep or you will get binary output
zmatrix.tofile(completeName,sep="\n")
Output is in the same format as above.
Calling str on the matrix will give you similarly formatted output to what you get when you try to print so that is what you are writing to the file the formatted truncated output.
Considering you are using python2, using xrange would be more efficient that using rane which creates a list, also having multiple imports separated by colons is not recommended, you can simply:
import numpy as np, os.path, os
Also variables and function names should use underscores z_matrix,zb_file,complete_name etc..
You shouldn't need to fiddle with the string representations of numpy arrays. One way is to use tofile:
zmatrix.tofile('output.txt', sep='\n')