Processing math: 100%
Ask Your Question
1

why sagemath can integrate a string?

asked 5 years ago

Nasser gravatar image

I am surprised this works. Sagemath 8.9

sage: var('x')
x
sage: integrate("x",x)
1/2*x^2

sage: type("x")
<type 'str'>

Why does sagemath accept string for the integrand? Should not this be type error? Maple:

restart
int("x",x)
Error, (in int) wrong number (or type) of arguments: wrong type of integrand passed to indefinite integration.
Preview: (hide)

1 Answer

Sort by » oldest newest most voted
3

answered 5 years ago

dsejas gravatar image

updated 5 years ago

Hello, @Nasser. This behavior is related to the code of the integrate function itself. If you execute integrate?? in your Sage session, you will be able to see the docstring of the subroutine, and its source code. We are interested in the source code right now:

if hasattr(x, 'integral'):
    return x.integral(*args, **kwds)
else:
    from sage.symbolic.ring import SR
    return SR(x).integral(*args, **kwds)

This basically verifies if the object you passed as argument (x in this code) has the integral attribute, which is nothing more than a subroutine that specifies how x should be integrated. If x doesn't have such an attribute defined, then Sage converts it into an element of the Symbolic Ring (SR).

In the case of your example, the string "x" does not have an integral attribute (since it's a string), so Sage calls SR('x'), which converts your string into the identity function, i.e. xx, whose integral is 1/2x2.

As particular examples, you can try:

f(x) = SR("x")
f(2)

This will return 2, as expected, showing you that you have actually define a function from its string representation. Now try:

(f(x)).integral(x)

which is equivalent to integrate(f(x), x) or integrate("x", x) of (SR("x")).integral(x). Finally, try:

f(x) = SR("sin(x)")
f(pi)
(f(x)).integral(x)
integrate("sin(x)", x)

EDIT Based on the answer to this question, I must point out that the use of strings as functions, by means of the Symbolic Ring SR, is discourage and should be avoided, because it has unpleasant consequences. This kind of use of strings seems not to be documented for that reason.

I hope this helps!

Preview: (hide)
link

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

Stats

Asked: 5 years ago

Seen: 381 times

Last updated: Dec 27 '19