I'm currently learning Python and I'm at the point in the book about using the Math library. I looked on the Python website and noticed the library was a bit scarce and am writing some more useful functions. For example, I went ahead and wrote a function to take coefficients and return the roots of the equation. Essentially a quadratic formula function. I'm wondering if it's possible to add this to the python Math library. If it isn't, how do I save it such that I can use that function in other Python programs I write just by calling it?
The math module is a builtin, so short of modifying the Python interpreter itself, I don't think you can modify it. However, writing a module is definitely something you can do.
If you structure your files like this:
somefolder mymath.py myprogram.py
...you could simply do
import mymath inside
myprogram.py, and use any functions or classes inside
mymath.py as normal.
mymath.py looks like this:
def quadratic(a, b, c): # blah blah blah
You could do the below inside
import mymath print mymath.quadratic(1, 2, 3)
If you want the module you've written available for any program, you could either copy-and-paste it into the folder of any project you're working on, or add it to your PATH. (For example, you could include
mymath.py inside the site-packages folder, which is located at
C:\Python27\Lib\site-packages on my computer). Once you do that, you should be able to do
import mymath without ever having to copy-and-paste anything.
As a side-note, numpy has a pretty comprehensive set of math and science related functions that you could check out. It's pretty much the de-facto standard for numerical computation in Python, afaik.