Ask Your Question
0

Speeding up symbolic nested loops

asked 2023-02-15 19:26:54 +0100

tolga gravatar image

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 flag offensive close merge delete

Comments

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

achrzesz gravatar imageachrzesz ( 2023-02-15 20:48:13 +0100 )edit

How x is defined?

Max Alekseyev gravatar imageMax Alekseyev ( 2023-02-15 21:19:33 +0100 )edit

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

@Max Alekseyev: x is a symbolic variable.

tolga gravatar imagetolga ( 2023-02-16 07:10:29 +0100 )edit

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-02-16 08:25:17 +0100

achrzesz gravatar image

updated 2023-02-16 14:49:08 +0100

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)])
edit flag offensive delete link more

Comments

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

tolga gravatar imagetolga ( 2023-02-16 08:54:20 +0100 )edit
1

RDF was motivated by the output from your oryginal code

achrzesz gravatar imageachrzesz ( 2023-02-16 12:42:42 +0100 )edit

The code was reedited according to @Max Alekseyev remarks

achrzesz gravatar imageachrzesz ( 2023-02-16 14:49:42 +0100 )edit

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: 2023-02-15 19:26:54 +0100

Seen: 277 times

Last updated: Feb 16 '23