# Speeding up symbolic nested loops

Is there a way to speed up the following nested loop?

reset()

mylimit=100

R = PolynomialRing(RR, 'a', mylimit)
a = R.gens()

func=0
for n in range(mylimit):
for i in range(n+1):
term1=(x^i)/(i+2)
for j in range(i+1):
term2=(x^(j+1))/(2*j+1)
for k in range(n-i-j+1):
term3=a[k]*(x^k)
term4=x^((n-k-i-j))/(2*(n-k-i)+1)
func=func+term1*term2*term3*term4

edit retag close merge delete

1

Using declarations

x=var('x')
a=var('a',n=mylimit)


and replacing divisions by integers by divisions by RDF(integers) one can finish in 3 minutes

( 2023-02-15 20:48:13 +0200 )edit

How x is defined?

( 2023-02-15 21:19:33 +0200 )edit

@achrzesz: This really speeds up the code. Thank you!

@Max Alekseyev: x is a symbolic variable.

( 2023-02-16 07:10:29 +0200 )edit

Sort by ยป oldest newest most voted

This is faster:

mylimit=100
x=var('x')
a=var('a',n=mylimit)

fun1=sum(
[sum(
[sum(
[sum([a[k]*x^(n+1)/RDF(((i+2)*(2*j+1)*(2*(n-k-i)+1))) for k in range(n-i-j+1)])
for j in range(i+1)])
for i in range(n+1)])
for n in range(mylimit)])


with numerically negligible differences (I hope)

For those who don't like SR:

mylimit=100
P = PolynomialRing(QQ,[f'a{i}' for i in range(mylimit)]+['x'])
a = P.gens()[:mylimit]
x = P.gens()[mylimit]
fun1=sum(
[sum(
[sum(
[sum([a[k]*x^(n+1)/((i+2)*(2*j+1)*(2*(n-k-i)+1)) for k in range(n-i-j+1)])
for j in range(i+1)])
for i in range(n+1)])
for n in range(mylimit)])

more

Thank you! This is much faster. If I remove RDF, it runs even faster.

( 2023-02-16 08:54:20 +0200 )edit
1

RDF was motivated by the output from your oryginal code

( 2023-02-16 12:42:42 +0200 )edit

The code was reedited according to @Max Alekseyev remarks

( 2023-02-16 14:49:42 +0200 )edit