Range


In the cells that follow we see Range can be used in a lot of cases where
Table is often used.  One difference  is that Range will normally make a list
in about half the time Table would need to make the same list.



Range doesn't  have to count over integers.  In the next line Range starts at
0 and counts in steps of 1/20  up to the last value less than (π/3).  
Notice (1<π/3), but (21/20>π/3), sot the list stops at 1.

Range[0, π/3, 1/20]

{0, 1/20, 1/10, 3/20, 1/5, 1/4, 3/10, 7/20, 2/5, 9/20, 1/2, 11/20, 3/5, 13/20, 7/10, 3/4, 4/5, 17/20, 9/10, 19/20, 1}

The next example is similar to the previous example.

Range[0, 1, π/20]

{0, π/20, π/10, (3 π)/20, π/5, π/4, (3 π)/10}


In the same line where Range makes a list, a listable function such as Times
or Power can be applied to the list as in the next line. The same list can be
made using Table, but Range is almost always faster.  If the function being
applied to each element of the list isn't listable, you can map it over the
list, and it will work about as fast as if it was listable.  In the two
following examples Power is applied to the list returned by Range.

Clear[x, n, a] ;  x^Range[n, n + 10, 2]

{x^n, x^(2 + n), x^(4 + n), x^(6 + n), x^(8 + n), x^(10 + n)}

The next line give an interesting example.

Range[a, a + 12n, 2n]

{a, a + 2 n, a + 4 n, a + 6 n, a + 8 n, a + 10 n, a + 12 n}

In the next line Range is used to make a series expansion for Cos[x].   Timing experiments show that this is much faster than using Series, but the  method below is fairly cryptic.  Also creating the series using Range  requires knowledge of the general form of each term, while Series doesn't  need this information.  The fact that Series must determine the coefficients  for each term is probably the reason why it takes much longer.  The #&  notation is explained in the discussion of Function.

Plus @@ (-(-1)^(#) x^(2# - 2)/(2# - 2) ! &[Range[7]])

1 - x^2/2 + x^4/24 - x^6/720 + x^8/40320 - x^10/3628800 + x^12/479001600


Created by Mathematica  (May 16, 2004)

Back to Ted’s Tricks index page