Menu

#826 prod for calculate product similarly to sum

Version 6
closed-accepted
nobody
None
5
3 days ago
2025-05-01
No

Attached patch is an implement of "prod" which calculates product of numbers similarly to sum.

1 Attachments

Discussion

  • Ethan Merritt

    Ethan Merritt - 2025-05-01

    I can see that this implementation should be sufficient for simple cases.

    This is not my area of expertise, so I do not feel confident of judging whether it is sufficient or optimal as the number of terms becomes very large or the magnitude of the individual terms becomes large.

    I worry that sequential multiplication can lead to overflow more often than sequential addition. There also may be concerns about loss of precision. For example, I wonder if there is a good way to decide when it would be better to evaluate a sum of logarithms instead?

    Product(start, end, <expression>)
        = exp( Sum(start, end, log(<expression>)) )
    

    Does anyone know what other programs do? R? Mathematica? Octave?

     
  • Shigeharu TAKENO

    I think the implementation by exp and log is not sufficient because each term may has minus sign.
    For example: Lagrange interpolation:

    array a[5] = [1.0, 2.0, 4.0, 8.0, 9.0]
    array b[5] = [2.0, 5.0, 1.0, 3.0, 2.0]
    f(x,a,b,n) = sum [j=1:n] (prod [i=1:j-1] (x-a[i])/(a[j]-a[i]))*(prod [i=j+1:n] (x-a[i])/(a[j]-a[i]))*b[j]
    set xrange [0:10]
    set xtics 1
    set grid
    plot f(x,a,b,5)
    
     
    • Ethan Merritt

      Ethan Merritt - 2025-05-10

      Good point about handling terms that are less than zero.

      Another question:
      What should happen if the end is less than the start?
      For example
      A = prod [ i = 5 : 4 ] i

      The code in the patch sets A to 1.0, but this is non-intuitive.
      I would expect it to set A to 5.0 or to report an error and set A to NaN or <undefined>.</undefined>

      Alternatively, the code could rearrange the terms so that the sequence of multiplications runs from min(start,end) to max(start,end). But this would be different from what "sum" currently does.

       

      Last edit: Ethan Merritt 2025-05-10
  • Shigeharu TAKENO

    I think it is reasonable that "prod [i=5:4] i" returns 1, since it is reasonable that "sum [i=5:4] i" returns 0.

    This behavior is also used in the Lagrange interpolation I showed, and it may be useful.

     
    • Ethan Merritt

      Ethan Merritt - 2025-05-12

      OK.
      Added to the git master by commit 2b27736ab8
      I added a description in the documentation.

       
  • Ethan Merritt

    Ethan Merritt - 2025-05-12
    • status: open --> pending-accepted
     
  • Ethan Merritt

    Ethan Merritt - 2025-06-03
    • status: pending-accepted --> closed-accepted
     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.