<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Conal Elliott &#187; integration</title>
	<atom:link href="http://conal.net/blog/tag/integration/feed" rel="self" type="application/rss+xml" />
	<link>http://conal.net/blog</link>
	<description>Inspirations &#38; experiments, mainly about denotative/functional programming in Haskell</description>
	<lastBuildDate>Thu, 25 Jul 2019 18:15:11 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=4.1.17</generator>
	<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=conal&amp;popout=1&amp;url=http%3A%2F%2Fconal.net%2Fblog%2F&amp;language=en_US&amp;category=text&amp;title=Conal+Elliott&amp;description=Inspirations+%26amp%3B+experiments%2C+mainly+about+denotative%2Ffunctional+programming+in+Haskell&amp;tags=blog" type="text/html" />
	<item>
		<title>Exact numeric integration</title>
		<link>http://conal.net/blog/posts/exact-numeric-integration</link>
		<comments>http://conal.net/blog/posts/exact-numeric-integration#comments</comments>
		<pubDate>Mon, 28 Dec 2009 18:22:43 +0000</pubDate>
		<dc:creator><![CDATA[Conal]]></dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[integration]]></category>
		<category><![CDATA[partial value]]></category>
		<category><![CDATA[unamb]]></category>

		<guid isPermaLink="false">http://conal.net/blog/?p=92</guid>
		<description><![CDATA[This post describes a simple way to integrate a function over an interval and get an exact answer. The question came out of another one, which is how to optimally render a continuous-space image onto a discrete array of pixels. For anti-aliasing, I&#8217;ll make two simplying assumptions (to be revisited): Each pixel is a square [&#8230;]]]></description>
				<content:encoded><![CDATA[<!-- 

Title: Exact numeric integration

Tags: integration, unamb, partial value

URL: http://conal.net/blog/posts/exact-numeric-integration/

-->

<!-- references -->

<!-- teaser -->

<p>This post describes a simple way to integrate a function over an interval and get an exact answer.
The question came out of another one, which is how to optimally render a continuous-space image onto a discrete array of pixels.</p>

<p>For anti-aliasing, I&#8217;ll make two simplying assumptions (to be revisited):</p>

<ul>
<li>Each pixel is a square area.  (With apologies to <a href="http://www.alvyray.com/memos/" title="Paper: &quot;A Pixel is Not a Little Square, a Pixel is Not a Little Square, a Pixel is Not a Little Square! (And a Voxel is Not a Little Cube)&quot; by Alvy Ray Smith">Alvy Ray Smith</a>.)</li>
<li>Since I can choose only one color per pixel, I want exactly the <em>average</em> of the continuous image over pixel&#8217;s subregion of 2D space.</li>
</ul>

<p>The average of a function over a region (here a continuous image over a 2D interval) is equal to the integral of the function across the region divided by the size (area for 2D) of the region.
Since our regions are simple squares, the average and the integral can each be defined easily in terms of the other (dividing or multiplying by the size).</p>

<p>To simplify the problem further, I&#8217;ll consider one-dimensional integration, i.e., integrating a function of <strong>R</strong> over a 1D interval.
My solution below involves the least upper bound operator <a href="http://conal.net/blog/tag/unamb/" title="posts on unamb and lub">I&#8217;ve written about</a> (and its specialization <code>unamb</code>).</p>

<!--
**Edits**:

* 2009-02-09: just fiddling around
-->

<!-- without a comment or something here, the last item above becomes a paragraph -->

<p><span id="more-92"></span></p>

<h3>A first simple algorithm</h3>

<p>Integration takes a real-valued function and an interval (low &amp; high) and gives a real.</p>

<pre><code>integral :: (R-&gt;R) -&gt; R -&gt; R -&gt; R
</code></pre>

<p>Integration has a property of interval additivity, i.e., the integral of a function from <em>a</em> to <em>c</em> is the sum of the integral from <em>a</em> to <em>b</em> and the integral from <em>b</em> to <em>c</em>.</p>

<pre><code>∀ a b c. integral f a c == integral f a b + integral f b c
</code></pre>

<p>which immediately leads to a simple recursive algorithm:</p>

<pre><code>integral f low high = integral f low mid + integral f mid high
  where mid = (low + high) / 2
</code></pre>

<p>Extending to 2D is simple: we could divide a rectangular region into four quarter subregions, or into two subregions by splitting the longer dimension.
The quartering variation is very like <a href="http://en.wikipedia.org/wiki/Mipmap">mipmapping</a>, as used to anti-alias textures.
Mipmapping takes a pixel array and builds a pyramid of successively lower resolution versions.
Each level except the first is constructed out of the previous (next higher-resolution) level by averaging blocks of four pixels into one.
The simple <code>integral</code> algorithm above (extended to 2D) is like mipmapping when we start with an <em>infinite resolution</em> (i.e., continuous) texture.</p>

<h3>Umm &#8230;</h3>

<p>Maybe you&#8217;re thinking what I&#8217;m thinking: Hey!  We don&#8217;t have a base case, so we won&#8217;t even get off the ground.</p>

<p>Given that our domain is continuous, I don&#8217;t know what to use for a base case.
So let&#8217;s consider what the purpose of a base case is, and see whether that purpose can be accomplished some other way.</p>

<h3>What&#8217;s so important about base cases?</h3>

<p>Does every recursion need a base case in order to avoid being completely undefined?</p>

<p>Here&#8217;s a counter-example: mapping a function over an infinite stream, taken from the source code of the <a href="http://hackage.haskell.org/package/Stream" title="Haskell package: Stream">Stream package</a>.</p>

<pre><code>data Stream a = Cons a (Stream a)

instance Functor Stream where
  fmap f ~(Cons x xs) = Cons (f x) (fmap f xs)
</code></pre>

<p>The key thing here is that <code>Cons</code> is <em>non-strict</em> in its second argument, which holds the recursive call.
(Definition: a function <code>f</code> is &#8220;strict&#8221; if <code>f ⊥ == ⊥</code>.)</p>

<p>Non-strictness of <code>if-then-else</code> is exactly what allows more mundane recursions to produce defined (non-⊥) results as well, e.g.,</p>

<pre><code>fac n = if n &lt;= 0 then 1 else fac (n-1)
</code></pre>

<p>In this <code>fac</code> example, <code>if-then-else</code> must be (and <em>is</em>) non-strict in its third argument (the recursive call).</p>

<p>So &#8220;base case&#8221; is not the heart of the matter; non-strictness is.</p>

<h3>Finding non-strictness</h3>

<p>The trouble with our elegant recursive derivation of <code>integral</code> above is that addition is strict in its arguments (where the recursive <code>integral</code> calls appear).
This strictness means that we cannot get <em>any information at all</em> out of the right-hand side until we get some information out of the recursive calls, which won&#8217;t happen until we get information out of <em>their</em> recursive calls, ad infinitum.</p>

<p>To escape this information black hole, can we find some scrap of information about the value of the integral that doesn&#8217;t (always) rely on the recursive calls?</p>

<p><a href="http://en.wikipedia.org/wiki/Interval_arithmetic" title="Wikipedia article">Interval analysis</a> (IA) provides an answer.
The idea of IA is to extend functions to apply to <em>intervals</em> of values and produce intervals of results.
The interval versions are sloppy in that a result interval may hold values not corresponding to anything in the source interval.
(In math-speak, a result interval may be a <em>proper</em> superset of the image of the source interval under the function.)</p>

<p>Applying an interval version of the function to the source interval results in lower and upper bounds for <code>f</code>.
The average must be between these bounds, so the integral is bounded by these bounds multiplied by the interval size.
(Or use more sophisticated variations on IA, such as affine analysis, etc.)</p>

<p>Now we have <em>some</em> information.
How can we mix it in with the sum of recursive calls to <code>integral</code>?
We can use <code>(⊔)</code> (least upper bound or &#8220;lub&#8221;), which is perfect for the job because its meaning is exactly to combine two pieces of information.
See <em><a href="http://conal.net/blog/posts/merging-partial-values/" title="blog post">Merging partial values</a></em> and <em><a href="http://conal.net/blog/posts/lazier-function-definitions-by-merging-partial-values/" title="blog post">Lazier function definitions by merging partial values</a></em>.</p>

<p>Instead of treating IA as operating on <em>intervals</em>, think of it as operating on &#8220;partial numbers&#8221;, i.e., inexact values.
Suppose we define a type of numbers that consistently generalizes exact numbers but is additionally populated with inexact values.</p>

<pre><code>type Partial R  -- abstract

between :: Ord a =&gt; a -&gt; a -&gt; Partial a
exact   :: a -&gt; Partial a
</code></pre>

<p>Perhaps <code>exact a = between a a</code>.</p>

<p>Now we can escape the black hole:</p>

<pre><code>integral f low high = ((high - low) * f (between low high)) ⊔
                      (integral f low mid + integral f mid high)
  where mid = (low + high) / 2
</code></pre>

<h3>Representation</h3>

<p>One representation of a partial value is an interval.
In this representation, <code>(⊔)</code> is interval intersection.</p>

<pre><code>type Partial a = (a,a)  -- first try

(l,h) ⊔ (l',h') = (l `max` l', h `min` h')
</code></pre>

<p>If the lower and upper bounds are plain old exact numbers, then this choice of representation and <code>(⊔)</code> has a fatal flaw.
The <code>max</code> and <code>min</code> functions are strict, so <code>(⊔)</code> can easily produce <em>less</em> information than it is given, while its job is to combine all information present in both arguments.
(For instance, let <code>l == 3</code> and <code>l' == ⊥</code>.  Then <code>l `max` l' == ⊥</code>, so we&#8217;ve lost the information from <code>l</code>.)</p>

<p>One possible solution is to change the kind of numbers used in the bounds in such a way that <code>max</code> and <code>min</code> are not strict.
Let&#8217;s use two new types, for lower and upper bounds:</p>

<pre><code>type Lower a  -- abstract
type Upper a  -- abstract
</code></pre>

<p>These two types also capture partial information about numbers, though they cannot express exact numbers (other than <code>maxBound</code> and <code>minBound</code>, where available).</p>

<p>Now we can represent partial numbers.</p>

<pre><code>type Partial a = (Lower a, Upper a)

(l,h) ⊔ (l',h') = (l ⊔ l', h ⊔ h')
</code></pre>

<p>Notice that I&#8217;ve replaced both <code>max</code> and <code>min</code> each by <code>(⊔)</code>.
Now I realize that I only used <code>max</code> and <code>min</code> above as a way of combining the information that the lower and upper bounds (respectively) gave us.
The <code>(⊔)</code> operator states this intention directly.</p>

<p>Pleasantly, we don&#8217;t even have to state this definition, as <code>(⊔)</code> is already defined this way for pairs.
(Well, not quite; see <em><a href="http://conal.net/blog/posts/merging-partial-values/" title="blog post">Merging partial values</a></em>.)</p>

<h3>Improving values and intervals</h3>

<p>This idea for representing partial values is very like what Warren Burton and Ken Jackson called &#8220;improving intervals&#8221;, which is a two-sided version of Warren&#8217;s &#8220;improving values&#8221; (corresponding to <code>Lower</code> above).
(See <em>Encapsulating nondeterminacy in an abstract data type with deterministic semantics</em> (JFP, 1991) and <em>Improving Intervals</em> (JFP, 1993).  As these papers are hard to find, you might start with <a href="http://ir.lib.sfu.ca/bitstream/1892/7097/1/b15233182.pdf" title="Ken Jackson's dissertation: &quot;Functional programming applied to parallel combinatorial search">Ken Jackson&#8217;s dissertation</a>.)</p>

<p>Warren and Ken represented improving values and intervals as lazy, possibly-infinite lists of improving approximations.
While an improving value is represented as a sequence (finite or infinite) of monotonically increasing values, an improving interval is represented as a sequence of monotonically shrinking intervals (each containing the next).
The <em>denotation</em> of one of these improving representations is the limit of the sequence.
Any query for information not specifically present in a partial value would yield ⊥, just as applying a partial function (or data structure) outside its domain yields ⊥.
For instance, one could ask a partial number for successive bits.
If a requested bit cannot be determined from the available bounds, then that bit and all later bits are ⊥.</p>

<h3>Dropping <code>lub</code></h3>

<p>There&#8217;s a subtlety in the second definition of <code>integral</code> above.
My goal is that <code>integral</code> yield a completely defined (exact) number.
We can meet this goal for fairly well-behaved functions, since IA gives decreasing errors as input intervals shrink, and the result intervals are multiplied by shrinking interval sizes.
Even discontinuities in the integrated function will be smoothed out, if there are only finitely many, thanks to the multiplication.</p>

<p>Completely defined values are at the tops of the information ordering.
(I&#8217;m assuming we don&#8217;t have the &#8220;over-defined&#8221; (self-contradictory) value ⊤.)
The sum of recursive calls is also fully defined, and starter partial value, <code>f (between low high)</code>, has strictly less information, i.e.,</p>

<pre><code>   (high - low) * f (between low high)
⊑  integral f low high
=  integral f low mid + integral f mid high
</code></pre>

<p>So we can get by with a less general form of <code>(⊔)</code>.
If we represent our numbers as lazy lists of improving intervals, then we can simply use <code>(:)</code> in place of <code>(⊔)</code>.</p>

<p>Hm.  My reasoning just above is muddled.
I think the crucial property is that</p>

<pre><code>     (high - low) * f (between low high)
⊑    (mid  - low) * f (between low mid )
   + (high - mid) * f (between mid high)
</code></pre>

<p>To see why this property holds, first subdivide:</p>

<pre><code>     (high - low) * f (between low high)
==   ((mid - low) + (high - mid)) * f (between low high)
==   (mid  - low) * f (between low high)
   + (high - mid) * f (between low high)
</code></pre>

<p>Next apply information monotonicity, i.e., more information (smaller interval) in yields more information out:</p>

<pre><code>f (between low high) ⊑ f (between low med)

f (between low high) ⊑ f (between med high)
</code></pre>

<p>from which the crucial property follows.</p>

<p><em>Note</em>: the notation is potentially confusing, since smaller intervals means more information, and so <code>(⊑)</code> means <code>(⊇)</code>, and <code>(⊔)</code> means <code>(∩)</code>.</p>

<h3>Efficiency and benign side-effects</h3>

<p>There is a serious efficiency problem with this (lazy) list-based representation of improving values or intervals, as pointed out by Ken and Warren:</p>

<blockquote>
  <p>At any point in time, it is really only the tightest bounds currently in the list that are important.  [&#8230;]  Hence, the list representation consumes more space than is necessary, and time is wasted examining the out-of-date values in the list.  A better representation, in a language that allows update-in-place, would be a pair consisting of the tightest lower bound and the tightest upper bound found so far.  This pair would be updated-in-place when better bounds become known.  (<em>Improving Intervals</em>, section 5.2)</p>
</blockquote>

<p>The update-in-place suggested here is semantically benign, i.e., does not compromise pure functional semantics, because it doesn&#8217;t change the information content.
Instead, it makes that content more efficient to access a second time.
The same sort of semantically benign optimization underlies lazy evaluation, with the run-time system destructively replacing a thunk upon its first evaluation.</p>

<p>This benign-update idea is also explored in <em><a href="http://conal.net/blog/posts/another-angle-on-functional-future-values/" title="blog post">Another angle on functional future values</a></em>.</p>

<h3>Averaging vs integration</h3>

<p>In practice, I&#8217;d probably rather use a recursive interval average function instead of a recursive integral.
Recall that with the recursive <code>integral</code>, we had to multiply by the interval size at each step.
The intervals get very small, and I worry about having to combine numbers of greatly differing magnitudes.
With a recursive average, the numbers get averaged at each step, which I expect means we&#8217;ll be combining numbers of similar magnitudes.</p>

<pre><code>average f low high = f (between low high) ⊔
                     average f low mid `avg` average f mid high
  where mid = low `avg` high

a `avg` b = (a + b) / 2

integral f low high = (high - low) * average f low high   -- non-recursive
</code></pre>

<p>Here&#8217;s a modified form that can apply to higher dimensions as well:</p>

<pre><code>average f iv = f iv ⊔ mean [average f iv' | iv' &lt;- subdivide iv]

mean l = sum l / length l

integral f iv = size iv * average f iv   -- non-recursive
</code></pre>

<h3>Exact computation</h3>

<p>The algorithms described above can easily run afoul of inexact numeric representations, such as <code>Float</code> or <code>Double</code>.
With such representation types, as recursive subdivision progresses, at some point, an interval will be bounded by consecutive representable numbers.
At that point, sub-dividing an interval will result in an empty interval plus the pre-divided interval, and we will stop making progress.</p>

<p>One solution to this problem is use <em>exact</em> number representations.
Another is to use progressively precise inexact representations.</p>
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=92&amp;md5=143ad6acb12aa7c5a850835fe8054e2b"><img src="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png" srcset="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@2x.png 2xhttp://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@3x.png 3x" alt="Flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/exact-numeric-integration/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=conal&amp;popout=1&amp;url=http%3A%2F%2Fconal.net%2Fblog%2Fposts%2Fexact-numeric-integration&amp;language=en_GB&amp;category=text&amp;title=Exact+numeric+integration&amp;description=This+post+describes+a+simple+way+to+integrate+a+function+over+an+interval+and+get+an+exact+answer.+The+question+came+out+of+another+one%2C+which+is+how+to+optimally...&amp;tags=integration%2Cpartial+value%2Cunamb%2Cblog" type="text/html" />
	</item>
	</channel>
</rss>
