Skip to content

Commit

Permalink
Two more examples.
Browse files Browse the repository at this point in the history
  • Loading branch information
athas committed Jun 26, 2024
1 parent 81ad7b7 commit 93c6920
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
2 changes: 2 additions & 0 deletions examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ for plotting or rendering graphics.
- [Ranges](examples/ranges.html)
- [Scans and reductions](examples/scan-reduce.html)
- [Parametric polymorphism](examples/parametric-polymorphism.html)
- [Exclusive scans](examples/exclusive-scan.html)
- [Gather and scatter](examples/gather-and-scatter.html)
- [Pipe operators](examples/piping.html)
- [Complex ranges](examples/complex-ranges.html)
Expand Down Expand Up @@ -76,6 +77,7 @@ for plotting or rendering graphics.
- [AD with dual numbers](examples/dual-numbers.html)
- [Variance](examples/variance.html)
- [Matching parentheses](examples/parens.html)
- [Evaluating polynomials](examples/polynomials.html)

# Automatic differentiation

Expand Down
16 changes: 16 additions & 0 deletions examples/exclusive-scan.fut
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
-- # Exclusive scans
--
-- There are two common ways of specifying [scans](scan-reduce.html):
-- inclusive and exclusive. In an inclusive scan, element *i* of the
-- output includes element *i* of the input, while for an exclusive
-- scan it only goes up to *i-1*. The `scan` functon in Futhark is an
-- inclusive scan, but it is easy to define an exclusive one:

def exscan f ne xs =
map2 (\i x -> if i == 0 then ne else x)
(indices xs)
(rotate (-1) (scan f ne xs))

-- ## See also
--
-- [Evaluating polynomials](polynomials.html).
23 changes: 23 additions & 0 deletions examples/polynomials.fut
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
-- # Evaluating polynomials
--
-- A polynomial of the *n*th degree comprises *n* coefficients and can
-- be evaluated at a specific value *x* as follows:

entry poly as x =
f64.sum (map2 (*) as (map (x**) (map f64.i64 (indices as))))

-- [Horner's method](https://en.wikipedia.org/wiki/Horner%27s_method)
-- is a well-known technique for evaluating polynomials using fewer
-- multiplications (in particular, avoiding the use of the power
-- operation). While normally expressed sequentially, it can also be
-- implemented in Futhark using an [exclusive
-- scan](exclusive-scan.html):

import "exclusive-scan"

entry horner as x =
f64.sum (map2 (*) as (exscan (*) 1 (map (const x) as)))

-- In most cases, the additional overhead of manifesting the result of
-- the `scan` exceeds the savings from not evaluating `**`, so `poly`
-- is often fastest.

0 comments on commit 93c6920

Please sign in to comment.