Archive

Posts Tagged ‘sympy’

How to solve a two-variable equation with Sympy

December 13, 2024 Leave a comment

Problem

You have a two-variable equation and you want to solve it with Python / Sympy.

Solution

Let’s see this example:

7x + 9y = 8
9x - 8y = 69

What is the value of ‘x’ and ‘y’?

We could solve it manually too, of course, but let’s say we have hundreds of these. So let’s solve it with Python using the Sympy library.

>>> import sympy as sp
>>>
>>> x = sp.symbols('x')
>>> y = sp.symbols('y')
>>>
>>> eq1 = sp.Eq(7 * x + 9 * y, 8)
>>> eq2 = sp.Eq(9 * x - 8 * y, 69)
>>>
>>> system = [eq1, eq2]
>>>
>>> sol_set = sp.linsolve(system, x, y)
>>> sol_set
{(5, -3)}
>>>
>>> 7 * 5 + 9 * (-3)
8
>>> 9 * 5 - 8 * (-3)
69
Categories: python Tags: , , , ,

Digits of PI (Part 2)

April 13, 2012 Leave a comment

On the Python mailing list I got some great answers on how to generate the digits of PI. Here I sum them up.

Solution 1
Tichodroma forwarded me to http://mail.python.org/pipermail/edu-sig/2006-July/006810.html.

Quote:

Here's a generator I coded up based on a paper by Gibbons:
   

Click to access spigot.pdf

It's simple to code, but I think you have to read the paper to figure out what it's doing. (I just translated some code, so I really can't tell you :-) In the paper, this was done in a lazy functional language. I was mostly interested to see how it would translate to a Python generator. # pi.py -- imlementation of Gibbons' spigot algorithm for pi # John Zelle 4-5-06 def pi_digits(): """generator for digits of pi""" q,r,t,k,n,l = 1,0,1,1,3,3 while True: if 4*q+r-t < n*t: yield n q,r,t,k,n,l = (10*q,10*(r-n*t),t,k,(10*(3*q+r))/t-10*n,l) else: q,r,t,k,n,l = (q*k,(2*q+r)*l,t*l,k+1,(q*(7*k+2)+r*l)/(t*l),l+2) Here it is in action: >>> import pi >>> digits = pi.pidigits() >>> for i in range(30): print digits.next(), ... 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 6 2 6 4 3 3 8 3 2 7 >>> Since this uses long ints, it slows down considerably after a few thousand digits. You might want to use psyco when generating really "deep" digits. --John

It generates the digits of PI one after the other. It works well bit if you want lots of digits, it gets really slow.

Solution 2
E. Woiski suggested using the library SymPy.

sudo apt-get install python-sympy
>>> from sympy.mpmath import mp
>>> mp.dps = 1000   # number of digits
>>> +mp.pi    # str(mp.pi)

Very fast and simple. The only problem might be that you need to install sympy.

Solution 3 (update, 20121128)
One of my students called G. Szegedi came up with this solution:

from bigfloat import precision
import bigfloat

str_pi = str(bigfloat.atan2(+0.0,-0.0,precision(1000)))

With the bigfloat package you can do high precision floating-point arithmetic.

Design a site like this with WordPress.com
Get started