# How to substitute variables in a rational function by numbers?

I have a program in which the first part needs to use a polynomial ring in a[1], ..., a[n]. In the last part of the program, I need to substitute a[i] in a rational function by some numbers. I define

Ra=PolynomialRing(QQ,'a',n0)
Fa=Ra.fraction_field()
a=Ra.gens()


For example, I have a rational function

r1=(a[1]^2+a[2])/(a[3]+2*a[4])


I tried the following:

a_random=[2,4,2,5]
for i in [1..4]:
a[i]=a_random[i-1]


But it has an error:

'tuple' object does not support item assignment


How to solve this problem? Thank you very much.

edit retag close merge delete

1

Like that

sage: Ra=PolynomialRing(QQ,'a',6)
....: Fa=Ra.fraction_field()
....: a=Ra.gens()
sage: r1=(a[1]^2+a[2])/(a[3]+2*a[4])
sage: r1(0,1,2,3,4,5)
3/11

( 2024-03-26 10:10:38 +0200 )edit

On a side note, indexing is Sage starts with 0, and so there is also variable a[0].

( 2024-03-26 21:11:25 +0200 )edit

Sort by » oldest newest most voted

Besides providing variable values as arguments suggested by @FrédéricC, one can use method .subs(), which allow arbitrary or partial substitution - for example:

r1.subs( { a[1]:2, a[4]:2*a[2]+a[3] } )

more