Ask Your Question

How can I readline a one-term polynomial from a user?

asked 2017-11-24 09:08:11 +0200

veritas gravatar image

updated 2017-11-24 10:21:47 +0200

I would like to ask the user for a function. How can I do that? Is there something like readline?

edit retag flag offensive close merge delete


What do you mean by a "one-term polynomial"?

As for the existence of a readline, you can either use read_data to read from a file, or any Python method to read data from a file. You can also read from the standard input, and then process the data you get. In particular, if you have a string representation s of some object of a class C, you can usually construct the object using C(s). For instance, if you define R.<x> = ZZ[], then R('x^2 + x + 1') returns the polynomial x^2 + x + 1. Using eval(s) will have the same effect here (since x is known to SageMath as the generator of the polynomial ring).

B r u n o gravatar imageB r u n o ( 2017-11-24 09:23:28 +0200 )edit

I would like the user to type a function in(the user of the programme).

veritas gravatar imageveritas ( 2017-11-24 10:21:56 +0200 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2017-11-24 10:41:18 +0200

tmonteil gravatar image

updated 2017-11-24 10:51:58 +0200

In Python, you can read a string from the user prompt with the function raw_input:

sage: a = raw_input()

sage: a

sage: type(a)
<type 'str'>

Then you can transform that string into a symbolic expression:

sage: b = SR(a)
sage: b
2*x + 3

sage: type(b)
<type 'sage.symbolic.expression.Expression'>

sage: sin(b)
sin(2*x + 3)

You can put it within a function:

sage: def user_square():
....:     print 'Please enter a function to be squared: ',
....:     a = raw_input()
....:     return SR(a)^2

sage: user_square()
Please enter a function to be squared:  cos(d)+sin(t)
(cos(d) + sin(t))^2

If you want to make something fancy, with input boxes and sliders, you can have a look at Sage interact.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2017-11-24 09:08:11 +0200

Seen: 363 times

Last updated: Nov 24 '17