Doing Math with Python by Amit Saha

Doing Math with Python by Amit Saha

Author:Amit Saha
Language: eng
Format: mobi, epub, azw3, pdf
Publisher: No Starch Press, Inc.
Published: 2015-08-25T04:00:00+00:00


Plotting Expressions Input by the User

The expression that you pass to the plot() function must be expressed in terms of x only. For example, earlier we plotted y = 2x + 3, which we entered to the plot function as simply 2x + 3. If the expression were not originally in this form, we’d have to rewrite it. Of course, we could do this manually, outside the program. But what if you want to write a program that allows its users to graph any expression? If the user enters an expression in the form of 2x + 3y – 6, say, we have to first convert it. The solve() function will help us here. Let’s see an example:

>>> expr = input('Enter an expression: ')

Enter an expression: 2*x + 3*y - 6

➊ >>> expr = sympify(expr)

➋ >>> y = Symbol('y')

>>> solve(expr, y)

➌ [-2*x/3 + 2]

At ➊, we use the sympify() function to convert the input expression to a SymPy object. At ➋, we create a Symbol object to represent 'y' so that we can tell SymPy which variable we want to solve the equation for. Then we solve the expression to find y in terms of x by specifying y as the second argument to the solve() function. At ➌, this returns the equation in terms of x, which is what we need for plotting.

Notice that this final expression is stored in a list, so before we can use it, we’ll have to extract it from the list:

>>> solutions = solve(expr, 'y')

➍ >>> expr_y = solutions[0]

>>> expr_y

-2*x/3 + 2

We create a label, solutions, to refer to the result returned by the solve() function, which is a list with only one item. Then, we extract that item at ➍. Now, we can call the plot() function to graph the expression. The next listing shows a full graph-drawing program:

'''

Plot the graph of an input expression

'''



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.