Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A "nicer" way to do the trapezoid rule with equally-spaced points...</p> <p>Let <code>dx = pi/n</code> be the width of the interval. Also, let f(i) be sin(i*dx) to shorten some expressions below. Then interval i (in <code>range(1,n)</code>) contributes:</p> <pre><code>dA = 0.5*dx*( f(i) + f(i-1) ) </code></pre> <p>...to the sum (which is an area, so I'm using dA for "delta area"). Factoring out the 0.5*dx, makes the whole some look like:</p> <pre><code>A = 0.5*dx * ( (f(0) + f(1)) + (f(1) + f(2)) + .... + (f(n-1) + f(n)) ) </code></pre> <p>Notice that there are two f(1) terms, two f(2) terms, on up to two f(n-1) terms. Combine those to get:</p> <pre><code>A = 0.5*dx * ( f(0) + 2*f(1) + 2*f(2) + ... + 2*f(n-1) + f(n) ) </code></pre> <p>The 0.5 and 2 factors cancel except in the first and last terms:</p> <pre><code>A = 0.5*dx(f(0) + f(n)) + dx*(f(1) + f(2) + ... + f(n-1)) </code></pre> <p>Finally, you can factor dx out entirely to do just one multiplication at the end. Converting back to sin() calls, then:</p> <pre><code>def TrapArea(n): dx = pi/n asum = 0.5*(sin(0) + sin(pi)) # this is 0 for this problem, but not others for i in range(1, n-1): asum += sin(i*dx) return sum*dx </code></pre> <p>That changed "sum" to "asum", or maybe "area" would be better. That's mostly because sum() is a built-in function, which I'll use below the line.</p> <hr> <p>Extra credit: The loop part of the sum can be done in one step with a generator expression and the sum builtin function:</p> <pre><code>def TrapArea2(n): dx = pi/n asum = 0.5*(sin(0) + sin(pi)) asum += sum(sin(i*dx) for i in range(1,n-1)) return asum*dx </code></pre> <p>Testing both of those:</p> <pre><code>&gt;&gt;&gt; for n in [1, 10, 100, 1000, 10000]: print n, TrapArea(n), TrapArea2(n) 1 1.92367069372e-16 1.92367069372e-16 10 1.88644298557 1.88644298557 100 1.99884870579 1.99884870579 1000 1.99998848548 1.99998848548 10000 1.99999988485 1.99999988485 </code></pre> <p>That first line is a "numerical zero", since math.sin(math.pi) evaluates to about 1.2e-16 instead of exactly zero. Draw the single interval from 0 to pi and the endpoints are indeed both 0 (or nearly so.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload