How to convert Math Formula to Python code? - python

Are there any easy ways to convert mathematical formulas to Python code?
Perhaps translators, web reference, specific book chapters, anything ~
For regular expressions there are programs such as Kodos and sites such as pythonregex.com, so I was hoping there would be something similar for formula notation and Python.

No, this isn't possible in general. There are mathematical functions that aren't computable (for example, see wikipedia/Halting_problem). There are other mathematical functions where it's just not obvious how to code them up (consider a difficult integral or differential equations). There are many books written on finding numerical solutions to these sorts of problems (you can find some links here: wikipedia/Numerical_analysis).
For simple cases, you can transcribe mathematical formulae directly, but any automated means of translation would require a formal language for writing mathematical formulae in what would be a programming language in itself. This would beg the question, since you would be trading writing mathematical formulae in one language with writing them in another.

You could try to make your own with sympy and pyparsing.

so how to convert a math formula into python?
well, i myself dont know pretty much of python (i am just a beginner) but i have got some tips to help you:
first, you should like calculate the formula using x and y (or a and b) and write that down on a paper.
lets say phythagoras theory ( which is kinda basic).
c2 = a2 + b2;
so you have to input those a and b and write this formula to calculate c (which will be c = sqrt a2 + b**2)
now lets say you dont know this formulas (i can hear you). then? well, you should search it up on internet, listen to its explanation and try to transform them to python.
this is like noobs advice, but you know - no easy ways in programming.
(well, just search it on internet, i guess?)

Related

Coding solution to code step by step algorithm-solver

This is a rather general question: There is this webpage which lets you calculate Eigenvalues, Eigenspaces, etc... It also gives you step-by-step solutions. Is there any coding language or module (preferably in Python) which makes it easier to code something like this, or must this be coded manually?
Thank you for your help.

Simplifying Equations with Python z3 API

I'm trying to learn how to accomplish a few things when working with expressions in the Python z3 API.
I would like to be able to simplify/reduce sets of equations that contain intermediate variables. Say I have the Equations (A = B && C) and (C = D || E). In z3 these would be represented as (Bool('A') == And(Bool('B'), Bool('C')) and (Bool('C') == Or(Bool('D'), Bool('E')). Is there some function or series of functions that can be used to produce the simplified and reduced equation (A = B && (D || E))?
I would like to be able to convert a z3 expression into sum of products form (i.e Or(minterm1, minterm2,...).
An efficient way of determining the logical equivalence of two boolean equations.
A way of returning a boolean equations as formatted strings (i.e NOT in the nested function form used to declare the function.)
If anyone has any insight on any of these items, your input would be very much appreciated. Also, if any further clarification as to what is desired is needed, please let me know.
Thanks,
Great questions.
No, not in general. You can get z3 to simplify equations, but your notion of "simple" is unlikely to match what it will consider simple for its internal purposes. People often ask for this feature, but it is in general a very hard problem, and not at all clear what's meant by simple. Having said that, z3 does have a notion of Goal and Tactic, and there is even a simplify tactic that you can use. It will simplify the formulas, but having it behave precisely the way you want it to behave is a fool's errand.
See this great resource on tactics and perhaps you can play around to see to get something that works for you: http://www.cs.tau.ac.il/~msagiv/courses/asv/z3py/strategies-examples.htm
The simplify tactic does have a som option, I believe. That might do the trick. Again, see the above link, where they have the example:
s = Then(With('simplify', arith_lhs=True, som=True),
'normalize-bounds', 'lia2pb', 'pb2bv',
'bit-blast', 'sat').solver()
The nugget som=True tells the solver to use sum-of-minterms. Again, your mileage might vary depending on the exact structure of your formulas, and z3 might introduce new names that might defeat the purpose.
Absolutely! This is what z3 excels at. Simply assert f != g where f and g are your equations. If z3 says unsat, then you know they are equivalent for all assignments to variables. If it gives you a model, that forms a counter-example to their equaivalence. (The negated-equality trick is very common in SMT solving: A formula is a tautology precisely when its negation is unsatisfiable. So, you can assert the negation of what you want and see if it comes back with unsat.)
Note that this is what SMT (and SAT) solvers excel at.
For any formula f you build, you can issue print f and it'll print it. But as you probably already observed, it will not look like your textbook logical formulas. The pretty-printer has some options to control its behaviour, but it's probably not quite what you want.
However, the API provides functions to walk down the AST and extract nodes as you wish. So, you can write your own pretty printer if you so desire. Doing so isn't terribly difficult, but that doesn't mean it's simple: There are many cases to consider and in my experience, such printers are usually not that hard to fool; i.e., produce something vastly worse for small changes to the input.
From a practical perspective, while z3 and its high-level APIs in Python, C, Java, etc., is capable of doing everything you want, it's not going to be out-of-the-box except for #3. My recommendation would be to code everything else yourself, and rely on z3 for checking equality where it excels at. Of course, this all depends on precisely what you're trying to do. Best of luck!

Algorithms for implementing analytic calculus

I'm interested in writing a program in Python that can parse a mathematical expression and carry out operations on it in algebraic form. Most of these will be pretty easy, something like 2x+5x+xy. My program would take this and return the simplified 7x+xy. However I'd also like to eventually extend it's functionality to calculus as well, so if it's given something like integrate: 5x it should be able to return (5x^2)/2 + c. I'm aware that for this the sympy library can be used, but I'm interested in implementing it myself as a learning process. Are there any algorithims that exist to carry out algebraic calculus for any arbitrary integral/differential I could implement, or is this a more daunting task I've set for myself here? Any reasources would be appreciated.
It might be worthwhile to ask why you're looking at doing this, and understanding the sorts of things that you want to be able to integrate, because I think you might not know that you've actually stumbled onto a very difficult question.
If you are looking for an exercise to learn about simple low level polynomial integration and python - ie. something of the form x^2 + 2x + 7 - and the idea is to learn about string manipulation and simple math, then by all means I think you should attempt to do this and see how far you can get. Look at the various math related libaries (like Sympy or Numpy) and see what you can get.
If you are looking to produce a powerful tool to be used for Calculus, then I think you should rethink your idea and consider using something like Wolfram Alpha. A project like this could take years and you might not get a good result from it.

Calculating adjusted p-values in Python

So, I've been spending some time looking for a way to get adjusted p-values (aka corrected p-values, q-values, FDR) in Python, but I haven't really found anything. There's the R function p.adjust, but I would like to stick to Python coding, if possible. Is there anything similar for Python?
If this is somehow a bad question, sorry in advance! I did search for answers first, but found none (except a Matlab version)... Any help is appreciated!
It is available in statsmodels.
http://statsmodels.sourceforge.net/devel/stats.html#multiple-tests-and-multiple-comparison-procedures
http://statsmodels.sourceforge.net/devel/generated/statsmodels.sandbox.stats.multicomp.multipletests.html
and some explanations, examples and Monte Carlo
http://jpktd.blogspot.com/2013/04/multiple-testing-p-value-corrections-in.html
According to the biostathandbook, the BH is easy to compute.
def fdr(p_vals):
from scipy.stats import rankdata
ranked_p_values = rankdata(p_vals)
fdr = p_vals * len(p_vals) / ranked_p_values
fdr[fdr > 1] = 1
return fdr
You can try the module rpy2 that allows you to import R functions (b.t.w., a basic search returns How to implement R's p.adjust in Python).
Another possibility is to look at the maths an redo it yourself, because it is still relatively easy.
Apparently there is an ongoing implementation in scipy: http://statsmodels.sourceforge.net/ipdirective/_modules/scikits/statsmodels/sandbox/stats/multicomp.html . Maybe it is already usable.
You mentioned in your question q-values and no answer provided a link which addresses this. I believe this package (at least it seems so from the documentation) calculates q-values in python
https://puolival.github.io/multipy/
and also this one
https://github.com/nfusi/qvalue

Robust Multivariate Polynomial Regression in Python

Is there an easy way to do a multivariate robust polynomial regression in Python? E.g.
y = a + bx_1 + cx_2 + dx_1x_2 + ex_1^2 + fx_2^2
and possibly higher degree terms, where a,b,c,d,e,f are constants and the x_i are the dependent variables (there could be more than 2).
I have a set of data plagued by outliers, so the normality assumption does not hold. I have not much knowledge of regressions, but I've found that there are 'robust' methods to deal with this problem. Unfortunately I have not been able to find an easy way to do this in Python, without having to code the entire method. Have I overlooked something? Or should I maybe use another more suited language, such as R? (Since I don't know anything of R, and this is part of a larger problem which I've coded in Python, I would rather do it in Python. But maybe learning R is more efficient than trying to do this kind of stuff in Python.)
Thanks in advance.
R is very well suited for this, and there are libraries that let you talk to R from Python, like RPy2
http://rpy.sourceforge.net/rpy2.html
And here is a tutorial on robust regression with R:
http://www.ats.ucla.edu/stat/r/dae/rreg.htm

Categories