Ask Your Question
1

Why do I have to define a function using python code def for the formatted output to work?

asked 2022-03-18 04:47:36 +0200

chazzs gravatar image

this code works:

def f(x,y):return (x-y)/(y+1)

#f(x,y)=(x-y)/(y+1)

h=0.1; n=10
x0=0;  y0=1
xn=x0; yn=y0
print("n      xn       yn")
print("-----------------------")
print("{:3.0f}{:7.1f}{:12.6f}".format(0,x0,y0))
for i in range(1,n+1):
    k1 = f(xn,yn)
    yn = yn+k1*h
    xn = xn+h
    print("{:3.0f}{:7.1f}{:12.6f}".format(i,xn,yn))

If you comment the def line and uncomment the f(x,y) line it won't output the formatted output, but would output print(i,xn,yn). It looks like the declaring of the function needs to be in python even though the loop works for both.

Why is this? C

edit retag flag offensive close merge delete

Comments

Welcome to Ask Sage! Thank you for your question.

slelievre gravatar imageslelievre ( 2022-03-19 14:52:12 +0200 )edit

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-03-19 15:41:26 +0200

dsejas gravatar image

Hello, @chazzs! By commenting the first line and uncommenting the third as you suggested, gives the following error message:

n      xn       yn
-----------------------
  0    0.0    1.000000

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_2545862/3479229349.py in <module>
     12     yn = yn+k1*h
     13     xn = xn+h
---> 14     print("{:3.0f}{:7.1f}{:12.6f}".format(i,xn,yn))

TypeError: unsupported format string passed to sage.symbolic.expression.Expression.__format__

(It is important that you include backtraces and error messages in your post so it is easier for us to address the problem.)

In simple terms, this message says that you are trying to convert a _symbolic expression_ to a _float_ expression. Unfortunately, SageMath currently does not support this conversion. I reported this a couple of years ago on this same forum. Here is the (still) open ticket and my original question.

Basically, f(x,y) = (x - y) / (y + 1) is a symbolic way of defining functions (i.e., symbolic functions), while the def way is more general. Until this problem is solved, you should stick with def is you want to use the value of a function in a formatted string.

Hope this helps!

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

Stats

Asked: 2022-03-18 04:44:09 +0200

Seen: 42 times

Last updated: Mar 19