Showing posts with label math. Show all posts
Showing posts with label math. Show all posts

Wednesday, December 9, 2009

Pouring a Cone-Shaped 40 For Archimedes

George Hart presents what he says is a calculus problem: What is the ratio of the surface area of [the double mobius] cut to the surface area of the usual planar bagel slice?

Calculus is not necessary to answer this question and I think there are some key insights if you kick it old-style.

Let's start with the easy part: The area of the regular "sandwich style" bagel cut.


The area here is simply the area of the outer circle minus the area of the inner circle.

π(ρ+r)2 - π(ρ-r)2 = 4πrρ

Now, on to the (Double) Mobius Bagel.


(This image is very confusing--refer to the above link for a better visualization of the bagel in 3D.) Note that the red and blue edges of the cut must be the same length because they are the same cut, just offset by π radians around the bagel. OK, now unroll the bagel into a cylinder.


The double mobius cut is now a slice through the center of a cylinder. If you imagine the knife traveling down the cylinder, it rotates 2π radians while traversing the length. (Aside: The solution to the question of how to make a true mobius cut in a bagel should now be easy to visualize.)

I'm going to argue that unrolling the bagel didn't change the cut area. If you imagine re-rolling this cylinder into a bagel, you'll see that one side stretches while the other side shrinks. The red and blue lines are symmetrically spaced around the cylinder, and the two edges are the same length in the rolled state, so the stretching and shrinking should be the same for both. But do the stretch and shrink cancel out?


The inner circumference of the re-rolled bagel will be 2π(ρ-r) = 2πρ-2πr.
The outer will be 2π(&rho+r) = 2πρ+2πr.

We get a stretch of 2πr with a shrink of -2πr. Therefore unrolling the bagel doesn't change the cut area.

Another way to think of it is with a trapezoid. If you shorten the top by the same amount that you lengthen the bottom while the height is constant, the area of the trapezoid is the same.

So the area of the cut in cylindrical form is the same as the area of the cut in bagel form. But what is that area? We need to deal with the twist. For this, we unroll the cylinder.


The width of this rectangle is the original cylinder length: 2πρ.
The height of the rectangle is the original circumference of the cylinder: 2πr.
By Pythagoras: b = sqrt((2πρ)2 + (2πr)2)) = 2π*sqrt(ρ2 + r2).

b is the length of the edge of the cut. The "depth" of the cut is 2r (i.e. the diameter of the "tube" of the bagel). Therefore the total area of the cut is 4πr*sqrt(ρ2 + r2).

This area is larger than the sandwich-style cut by a factor of ρ/sqrt(ρ2 + r2).

Tuesday, July 21, 2009

Puzzle

Another hard one from the problem-a-day calendar.

My officemate and I discussed this one on-and-off throughout the day, drawing and redrawing many extra lines and triangles. We did finally solve it, but by a kind of questionable meta-method. Here's the basic idea:

Imagine blowing up the circle just a little bit. The line on the left can still be 12 units long. It will still be possible to have another line cut a chord 7 units long. And it will still be possible to have those two lines meet at a point. The angle they form will be different, though, and the value of x may be different. But the angle isn't a given and neither is the diameter of the circle. Therefore that problem is the same problem as this one. Since we know this puzzle has a unique solution, the value of x must actually be a constant and we can make that angle whatever we want. We will make it such that the chord is actually a diameter.

From that point the puzzle is easy and this method did yield the correct answer. The questionable part is assuming there was a unique solution. If we had come across this puzzle "in the wild" this wouldn't have been at all kosher. So how did the first person solve this puzzle? What's the real solution?

Thursday, January 15, 2009

Quickie

I got a Math-Problem-a-Day Calendar for Christmas. It's kind of a disappointment because the answer to each problem is the number of that day and a lot of these are barely even math problems, such as 20+0*sqrt(9).

That said, it is definitely possible to have good math problems where you know the final answer but the puzzle is how to get there. Yesterday's, which I just finally solved today, is a good example.

2.8 + 2.24 + 1.792 + 1.4336 + 1.14688 + 0.917504 + ...

The sum is yesterday's date, 14. But I couldn't figure out what this series was until someone (who happens to have this same calendar, btw) stopped by my office and mentioned Ramanujan. That got us talking about continued fractions (i.e. "I don't get continued fractions." "Me neither."). Which is all the hint I'm going to give for now...

Tuesday, January 6, 2009

Incremental Backup

  • So far, I've lost about 55 lbs. That's 4 or 5 pant sizes, I think, plus now my winter coat doesn't fit anymore. Naturally my workplace has NOW decided to have a Biggest Loser contest. I could have won one of these fabulous prizes! I'm almost tempted to regain it all so I can lose it for the free iPhone. (Actual prize may vary.)

  • The PVC piston idea doesn't work. Or rather, it works really well, but not for high temperatures. Maybe a water pumping thing might work, but otherwise it just gets gummed up with melty yuck. Also using insulation for the displacer is contraindicated as a fire hazard. /turns off smoke alarm. Needless to say, the engine was unsalvageable.

  • Because of the above, I'm starting a new engine. For various reasons, probably all stupid, I'm thinking of going rhombic. I sat down the other day to quickly figure out the stroke length given stuff like the gear diameter. Just an easy little geometry problem until my face imploded. Also, finding cots (commercial/off-the-shelf) hardware that can be used for a medium-sized Stirling is non-trivial.

  • This cool thing is in free beta. I hope that doesn't mean they are going to charge for it later, because then we won't have future classics like Two Regular Guys.

  • I got a Moleskine "square" (i.e. graph) paper notebook for Christmas. Coupled with my mechanical drawing pencils, it is really awesome. I should post some pics of what I've been doing with it.

  • Read Clock of the Long Now. It was very interesting and enlightening and life-changing and so forth, but they left out sufficient detail for my geekiness: Details on the mechanism. It's a single-function, mechanical, binary computer. Like the Difference Engine only in binary. Should be a snap to implement in Lego. I even started designing it but I just don't have enough time to do more than that.

Tuesday, September 16, 2008

Wooo

  • I cracked 50 lb of weight loss today. I'm still on track (±ε) to reach my original goal by Christmas. It also happens to be, as of yesterday, 10 lbs in 100 days, or almost exactly 350 calories/day.
  • Pursuant to that, I have made a breakthrough in food reduction technology. One of my favorite meals is...undocumented on this site?! WHAT. Anyway, it involves guacamole. The problem I've had is that I need to make enough to use up an entire avocado, which now that my metamabolism needs fewer calories is a little too much. Avocado turns brown if you look at it funny, so I can't put the excess in the fridge. I also can't throw it away because of the starving children in Africa. However, it turns out to freeze just fine. So now I can make M/Nths of a recipe which not only vastly reduces the hit points but also means I only use M avocados every N days.
  • I'm trying to embed a microcontroller into a project that I'll describe more later. All I know is Arduino, so I'm going with that. (I guess I could just use the Atmega chip or however that works, but baby steps, people.) The basic Arduino is a little unwieldy for this, but last night I finished soldering and testing the Really Bare Bones Board. And besides being much smaller and breadboard-compatible, it's also much cheaper because it pushes some of the cost of the unit into a one-time-purchase cable.
  • Number One Son, age 9, is trollering me. He just found out about HTML and has made a couple of pages. (With random size changes and font colors, naturally.) He keeps calling the .html file a "program".

Wednesday, September 10, 2008

New Control Structure Considered Useful

We have a large data processing problem at work. Basically, we get thousands of items every day and have to figure out which ones go together. The only way to know if they go together is to try them. Some items may not go with anything, some may fit with a hundred or more other items. The one nice thing is that once we've found 3-5 items that go together, we can zip through all the other members of the group.

The problem is finding those 3-5 items. Choosing every possible combination of 5 would take too long. Choosing every combination of 3 is fast enough, but leaves a lot of extras. The simple solution is to first try all the combos of 3, then try all the combos of 4 on the remainder, then try all the combos of 5 on the remainder of that. The smaller and smaller pile makes the larger and larger choices feasible.

My boss, who is a competent practical programmer, suggests we have 3 procedures: One that does a 3 nested loop, one that does a 4, and one that does a 5. Like this (in Tcl):

set items {apple orange banana grape strawberry}
set count 5

for {set i 0} {$i < $count} {incr i} {
    for {set j [expr $i + 1]} {$j < $count} {incr j} {
       for {set k [expr $j + 1]} {$k < $count} {incr k} {
         set string [lindex $items $i]
         lappend string [lindex $items $j]
         lappend string [lindex $items $k]
         puts $string
       }
    }
}

That's just the 3 level loop because the other two look almost the same. The 4 and 5 level loops are identical except for having additional levels. As a programmer who values elegance over readability, the phrase "identical except for" is a red flag. Why have 3 separate procedures when all you are adjusting is a single parameter? What I need is a new control structure that is basically a for loop but lets me control how many nested fors there are.

Tcl makes it easy to create new control structures. Here's the control structure definition:

# Usage:
#  indexcount - how many items are being chosen
#  itemcount  - how many items are being chosen from
#  indexvar   - variable to hold current combination of indexes
#  body       - code to execute for each combination
proc chooseloop {indexcount itemcount indexvar body} {

    if {$indexcount > $itemcount} { 
      error "More indexes than items"
    }

    if {$indexcount == 0} { return }

    set indexes {}
    for {set i 0} {$i < $indexcount} {incr i} {
       lappend indexes $i
    }

    set maxindexval [expr $itemcount - 1]

    while {1} {
 
       # make new body that sets indexvar first
       set newbody "set $indexvar {$indexes}\n$body"

       # do this iteration
       uplevel 1 [list eval $newbody]

       # find incrementable index
       set found no
       for {set i 0} {$i < $indexcount} {incr i} {
          set index [lindex $indexes end-$i]
          set thismax [expr $maxindexval - $i]
          if {$index < $thismax} {
             set found yes
             break
          }
       }

       if {!$found} { break }

       # increment this index and set all following ones
       set incrindex [expr ($indexcount - 1) - $i]
       set precedingval [lindex $indexes $incrindex]
       for {set j $incrindex} {$j < $indexcount} {incr j} {
          lset indexes $j [expr $precedingval + 1]
          set precedingval [lindex $indexes $j]
       }
    }
}

Now to get my 3 level loop, I can call like this:

chooseloop 3 5 indexes {
    set str ""
    foreach index $indexes {
       append str "[lindex $items $index] "
    }
    puts $str
}

In order to do 3, then 4, then 5, I can call like this:

for {set i 3} {$i < 6} {incr i} {
    chooseloop $i 5 indexes {
       set str ""
       foreach index $indexes {
          append str "[lindex $items $index] "
       }
       puts $str
    }
    puts "--"
}

The output of that last one is:

apple orange banana 
apple orange grape 
apple orange strawberry 
apple banana grape 
apple banana strawberry 
apple grape strawberry 
orange banana grape 
orange banana strawberry 
orange grape strawberry 
banana grape strawberry 
--
apple orange banana grape 
apple orange banana strawberry 
apple orange grape strawberry 
apple banana grape strawberry 
orange banana grape strawberry 
--
apple orange banana grape strawberry 
--

Tuesday, June 17, 2008

Potpourri

  • The diet hit a plateau. I'm down by 43 lbs from when I started, but in the last 30 days it's only changed by .5 lb. Looking at the chart from a year ago, I think I see a pattern. It was going down very slowly in May/June 2007, too. Looks like maybe 3 lbs in 60 days.

    There's probably two things going on. First, every year I imagine early summer weight loss should be easy. "Winter hibernation pounds just melt away naturally!" Second, a lot of good, fresh food shows up at the store.


  • I used to listen to Pandora at work. The advertised feature, discovery and laser(ish) targetting of your tastes, worked great. The problem was that the selection wasn't so great. I was down to about 30 songs that they just endlessly looped for me. Then I switched to Last.fm. The targetting isn't very good, but the selection is pretty huge. Exhibit A probably says more about how out of the loop I am for just now finding this, but still: Pretty hilarious (Lyrics)

  • And speaking of nerds: Do you like math? Do you also like mechanical devices? Then you will probably love How Round Is Your Circle. It's filled with mechanical ways to make, or approximate, mathematical functions, such as for linkages. The main problem with the book is that it's too short. It should really be a set of volumes so he can better explain each item. (Video teasers).

  • I have dismantled and cannibalized the Squeezer for a much simpler version of a parabolic trough now in production. Stay tuned!

Wednesday, January 23, 2008

The Parable of the Parallel Parabola

OK, so....man, I wish I'd been detailing every little step so I wouldn't have to regurgitate it all up in a huge mass. I'll try to make this short.

First of all, I used my calculation to make a simple parabolic reflector. I just plotted it out on graph paper and then set a few nails as guides to hold the mirror in place. This actually worked really well. (Even more surprising in light of how poorly the (first!) oven-formed one came out. More about which below.)

The one on the right has a black dot where I pre-calculated the focus to be, the one on the left is just a different focal length.

Now then. Having a single strip mounted with nails isn't that useful to me, so I want to mass produce these. Can't use the nail thing as a form since it'll just bend unevenly. I spent quite a few days trying to figure out how to make a jig that would cut a perfect parabola, but it was too hard (I still have some ideas on that, though, but that's another 2 or 3 posts). (And before you tell me, I know all about the T-square and string method of drawing one.) I eventually decided to just freehand follow a line.

So I had my shop assistant cut a parabola for me and I sandwiched the mirror in there. (My shop assistant is my father-in-law down the street who actually owns a bandsaw.)

(Other item of note: I originally wanted to have the mirror soften and sink down into shape, but that creates alignment problems. Instead I clamped the bendy strip cold. But that means it's hard to tell when I've reached temperature. So I put a probe down into the coldest part of the thing. The tip of the temperature probe is resting right on the mirror, so when that gets up to ~210°F, I can stick a fork in it. This takes like 2 hours--wood is a really great insulator, unfortunately.)

(Oh also: You can't see it, but there's a little alignment peg sticking out of the convex part of the form. There's a corresponding hole in the concave part so it can stick through. There's also a hole in the middle of each mirror. If I put each mirror on the peg, then after I'm done with all of them, I can line them up perfectly. So clev.)

The result: Not so great.

How could that possibly be? How could a few nails hastily thrown together at a few points make a better parabola than a careful, full-contact form?

Then a phrase floated up out of the darkness1. The curve parallel to a parabola is not another parabola. Just think about that for a minute. If you have a parabola and you want to make a curve parallel to it, you can't just take the same parabola and shift it up. Nor can you use some other parabola. (Read the gories yourself, it's pretty cool. If you like that sort of thing.)

So if you cut a parabolic form and sandwich it around a mirror, FOR EXAMPLE, then you are probably going to get the wrong shape because the two halves want to be parallel (i.e. separated by the thickness of the mirror) but can't. Wellity wellity wellity.

I took the equations in that paper and made a little program2 that would generate an SVG file of the shapes I wanted. Now I can take those back to my shop assistant and have him cut it out again.

(Note to anyone who actually reads this far, runs the program, examines the output and starts wondering: The curves aren't really all that different. I think the issue isn't so much that the curve is wrong, but that the poor alignment doesn't provide even pressure across the entire mirror. So it ends up wibbly-wobbly rather than smooth. Then again, the freehand wood parabola isn't all that smooth either, so maybe THAT'S the source of the error. The nail method at least creates a smooth curve, even if it isn't mathematically perfect.)

1I think it came from Practical Conic Sections, a really rip-roaring tale that I've been reading to the kids at bedtime. But seriously, it's very clear and pretty practical.

2

#!/usr/bin/python

# p1 and p2 are parallel to the parabola, i.e. a constant distance
# away *along the normal to the parabola*.

# For a curve C with generated by the function y = f(x), the parallel
# curve C' is given parametrically by:

#                 y'
# X = x - k -------------
#           sqrt(1+(y')^2)
#
#                 1
# Y = y + k -------------
#           sqrt(1+(y')^2)

# where k is the distance of the parallel from the curve.

# For derivation, see "The Curve Parallel to a Parabola is not a
# Parabola" by F. Max Stein.

import math

print '<?xml version="1.0" standalone="no"?>'
print '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"'
print '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'
print '<svg xmlns="http://www.w3.org/2000/svg"'
print '    width="8.5in" height="14in">'

focallength = 2.5
a = 1/(4.0 * focallength)
mirrorwidth = .125

vertoffset = 7
horizoffset = 2
phorizoffset = 2
prevx = 0
prevy = 0
pprevx = 0
pprevy = 0
first = True
x = -5.5
while x <= 5.5:
    y = a*x*x
    px = x - (mirrorwidth * 2 * a * x)/(math.sqrt(1 + (2*a*x)**2))
    py = y + (mirrorwidth * 1)/(math.sqrt(1 + (2*a*x)**2))
    if not first:
        print '<line x1="%.2fin" y1="%.2fin" x2="%.2fin" y2="%.2fin" style="stroke:black;stroke-width:2"/>' \
              % (prevy+horizoffset, prevx+vertoffset, y+horizoffset,x+vertoffset)
        print '<line x1="%.2fin" y1="%.2fin" x2="%.2fin" y2="%.2fin" style="stroke:red;stroke-width:2"/>' \
              % (pprevy+phorizoffset, pprevx+vertoffset, py+phorizoffset,px+vertoffset)
    prevx = x
    prevy = y
    pprevx = px
    pprevy = py
    x += .125
    first = False

print '</svg>'

Friday, January 11, 2008

Parabolae Foci

I keep having to solve this problem. It's not hard, but to "save time" I usually google it and find too much information and not enough explanation. Then I end up solving it myself. And it's so easy that each time I figure it out I'm like "there's no need to write this down--it's obvious BY INSPECTION". And then I forget it. So here it is:

Where is the focus of a parabola? Alternatively, what formula should I use to create a parabola with a given focus?

Take the equation y = ax2. Obviously the focus will be on the y-axis, but how far up? We know all the incoming rays will meet there, so let's choose a convenient one. A great choice is a ray that is turned by 90°. That is, it comes in vertically, hits the parabola, and heads towards the focus horizontally.

Since the angle of incidence equals the angle of reflection, the slope of the parabola at the point the ray hits is going to be 45°. (I spent like 20 minutes using gnuplot and the gimp trying to illustrate this before giving up. Just visualize it.) Where on a parabola is the slope 45°? Slope is also rise/run, so the the slope in the y = mx + b sense is 1. Where is the slope 1?

The equation was y = ax2. The instantaneous slope is the derivative, y' = 2ax. We want that to be 1.

2ax = 1
x = 1/2a

Substitute in to find out where on the y-axis this is.

y = ax2
y = a(1/2a)2
y = 1/4a

Now let's say I want to make a parabola with a focus that is 6 inches from the bottom of the curve.

1/4a = 6 inches
a = 1/24 inches

Therefore my equation in inches should be: y = .0416x2. (I think. Contradicting my claim about how easy this is is the fact that I actually got this wrong on paper, TWICE, before posting this.)

Monday, October 1, 2007

How To: Lose Weight (And I Don't Even Mention Lettuce!)

First of all, let's define our terms. There's "losing weight" and there's "getting healthy". For the latter, you need to eat carrots and exercise. I'm not too interested in carrots and, while I don't mind incidental exercise, I don't have the time or inclination to run around for no direct reason. This post is solely about making the number on the scale be smaller. That in itself is a great step towards "getting healthy", though, as long as you aren't too stupid about it (i.e. no starvation).

The mantra in diet books is "don't diet--change your lifestyle". Partly this is just a good idea. They don't want you going on a crash diet and then fattening back up. But partly this is making a virtue of necessity. The reason they want you to change your lifestyle is that a non-starvation diet doesn't change your weight fast enough to notice it unless you try it over the long term. That is, if you only drop .4 lbs in a week, are you really going to notice it adding up even over the course of a month, if you last that long? Who is going to remember, to the tenth of a pound, what they weighed 2 weeks ago? The first secret of losing weight: You need to keep a history of your progress to refer back to.

But if you are only losing .4 lbs/week, there's another problem: Noise. The key to controlling a variable to to be able to measure it accurately. Otherwise how do you know if what you are trying is working? But diet books also tell you not to weigh yourself very often. The reason they give for this is that your weight can vary because of non-fat variables. A large meal only partially digested, extra water, etc.

That's really terrible advice, though. For instance, children's test scores vary a lot from child to child, so should you just choose one random child from each school to measure performance? Of course not! If anything, taking fewer measurements increases the noise problem. The way to fix noisy data is to remove the noise. The second secret of losing weight: Noise reduction.

One simple way to remove noise from data is via averaging. Particularly, a "moving average". Let's say I take the following daily measurements:

Mon: 201
Tue: 201
Wed: 202
Thu: 201
Fri: 201
Sat: 202
Sun: 200
Mon: 201
Tue: 200
Wed: 200
Thu: 199
Fri: 200
Sat: 201
Nothing is happening! This diet sucks!!!

But wait, let's try doing a moving average. For each day, we'll average in with the previous two days (which means we have to skip the first two since there aren't two days before them).

Mon: 201 (no avg)
Tue: 201 (no avg)
Wed: 202 (201.3)
Thu: 201 (201.3)
Fri: 201 (201.3)
Sat: 202 (201.3)
Sun: 200 (201)
Mon: 201 (201)
Tue: 200 (200.3)
Wed: 200 (200.3)
Thu: 199 (199.6)
Fri: 200 (199.6)
Sat: 201 (200)
In fact, I lost a pound to 1.3 pounds, depending on where you count from. (There are many ways to doing a moving average, including ways to weight the average more heavily towards more recent measurements. Don't worry about the specific method here.)

The difference between raw and averaged (aka "smoothed") data is even more dramatic if you look at a graph. The circles are (fictitious-but-realistic) readings from the scale. The line is the smoothed average. Some of those weigh-ins differ by as much as 2 pounds in a single day. If you wake up a day after "being good" on your diet and see you weigh 2 pounds more than yesterday, doesn't that make you want to give up? But after you smooth the data, the problem may not be so bad.

In fact, it might not be a problem at all. Say the 3 days you were averaging yesterday were 205,202,201 (202.6). All you ate yesterday was carrots, but today you got 203. The weighted average is still 202, which is down from yesterday's average. How awesome is that!

Answer: Very awesome. But not so awesome we need to make things harder for ourselves. For instance, try to weigh yourself under the same circumstances every time: Same time of day, same state of undress, same fullness of stomach and bladder, etc. Also, I have gotten into the habit of "unofficially" weighing myself at various times throughout the day and I've gotten to know exactly how much to subtract for my clothing, how much water I'll lose via respiration overnight, etc. If I weigh X when I got to bed, I will weigh between X-3.5 and X-3 in the morning, rock-solid. An unofficial weigh-in the evening before can help prevent sticker shock in the morning and will also tell you if you can afford a bowl of ice cream. (That might not work for you.)

But who wants to juggle a bunch of numbers?! That's worse than being fat! Don't worry, you don't have to do a thing. Just head on over to PhysicsDiet. Create a free account, give it some info like your starting weight (you can ignore all the stuff about percent bodyfat and exercise) and away you go. The site handles the moving average and plots pretty charts and everything.

Since I started in late March I've only been losing an average of .44 lbs/wk. That's slow enough that I would have given up after a couple weeks, especially since it's also far less than the noisiness of the data (particularly since my scale only weighs in .5 lb increments). But with the two secrets of losing weight, historical progress and noise reduction, I've managed to lose over 15 lbs so far. Also, there are 3500 calories to a pound of fat, so that's just an average of 220 calories per day, which I barely even notice missing from my plate, let alone do I have to eat carrots and rice cakes. It's like I'm not even dieting (almost).

Monday, September 17, 2007

A New Recipe for π

I've been working on a Difference Engine in Lego. A little derivative perhaps, but still a big challenge. For one thing, there's not that much construction detail at that site. For another, what little there is I'm ignoring. I want to try to solve this on my own.

I've made some progress, but my (borrowed) video camera is being cranky so I've been unable to record and post it. (Aside to person I borrowed it from: I'm just getting a black screen in record mode. Also a little red flashing light that I think is the button battery so I thought that was it. However recording suddenly started work despite that, but only for a few minutes. ???) Thus this post isn't about that.

When the Difference Engine actually is running, I thought it would be fun to have it calculate π. NO WAIT, LET ME FINISH!!! I know π is transcendental, meaning there is no polynomial for which π is the solution.

The point of the Difference Engine is that as you crank the handle, you calculate the value of the polynomial for higher and higher values of x. What I'd like is a polynomial such that for higher and higher x, the value is closer and closer to π.

So I just google for a polynomial that does that, right? I mean, there must be hundreds of them by now. No. There are none that I can find.

There are plenty of series approximations, however. For instance:

π = 1/1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 +....

And with some series...es, it's possible to come up with an expression that the series sums to up to any given point. For instance, the sum of the first n odd numbers:

1 + 3 + 5 + 7 + .... 2n-1 = n2

So maybe one of the series approximations of π can be manipulated into a polynomial. Then I can use the Lego Difference Engine on that polynomial and crank out 2 or 3 digits.

However, I'm having a great deal of trouble with this (not that that indicates anything other than the fact that I'm really not that great at math). For one thing, I've concentrated my efforts on the simple-to-remember 1/1 - 1/3 + 1/5 approach. But I just realized this morning that this series alternately overshoots and undershoots the target, meaning it has an infinite number of humps and valleys. A polynomial of degree n can have a maximum of n-1 humps and valleys, AFAIK, so that series is out.

If I'm going to start from a series, I need one that's always more or less than π and never the other. Or an entirely different idea. I can think of plenty of iterative methods, but that's basically just a series. I need a single step where the accuracy is chosen by the value of x I input. Since I haven't been able to find any reference to such a thing, I'm thinking it hasn't ever been done. Is that because it's impossible?

Monday, August 27, 2007

Difference Engineering

I've known about Babbage's Difference and Analytical Engines for a long time, but never known much about how they work. Finally I actually read a little information on the first one (in the context of Legos) and it's pretty interesting from both a mathematical and mechanical point of view. Based on the information on that page, I worked out a tiny additional step of my own (though surely Babbage himself already knew this).

First of all, the basic idea: The purpose of the Difference Engine was to pre-calculate tables of polynomials for books in the days before portable calculators. So you'd want to known 3x3 + 14x2 + 5 for all values of x from 1 to, say, 1000. As it happens, there's a clever little shortcut such that if you have a few values you can calculate the next one very simply using only addition from the previous answer (thus "Difference Engine").

So let's say f(x) = x2 + 3x.


x   f(x)   diff1  diff2 
1     4      -      -   
2    10      6      -   
3    18      8      2
4    28     10      2
5    40     12      2
See that second difference column is a constant. If we'd picked a polynomial of the 3rd degree, we'd have to work this out to the 3rd column. Fourth degree, 4th column, etc.

So to build a machine, all you need to do is set the value for x = 1 and set the Nth difference in the last column. It automatically adds that difference to the previous difference, which is cascaded upwards until f(x + 1) is arrived at. Then you go around again. All that is required is simple addition.

What isn't explained on that page (that I saw) was how to know ahead of time what that last difference is going to be. Sure, you can work out N rows to get that Nth column, but it would be nice if you could set the inputs from direct inspection of the polynomial. As a matter of fact, this is easy.

Say f(x) = ax2 + bx + c. Then the difference between two successive answers (i.e. the value in the first difference column) is going to be:

a(x+1)2 + b(x+1) + c - ax2 - bx - c
= ax2 + 2ax + a + bx + b + c - ax2 - bx - c
= 2ax + a + b

The difference between successive entries in THAT column are going to be:

2a(x+1) + a + b - 2ax - a - b
= 2ax + 2a + a + b - 2ax - a - b
= 2a

And if we look at our example, we did indeed get 2 * 1 as the constant in the last column.

Working this out for a 3rd degree polynomial gives 6a (where a is the coefficient of x3). Based on these two examples and looking at Pascal's Triangle, I predicted the value for a 4th degree would be 20. But it was actually 24.

In fact, if you work it out it should be clear that the constant difference will be a * n!, where a is the coefficient of the highest power of x and n is that power. It should be simple to prove this using induction, since all other terms always drop out and you muliply the coefficient by the power at each step on the way down.

So if I wanted to know what the constant difference was in the 5th column of differences for the polynomial 8x5 - 3x3 + 117, I just multiple 8 times 5! and get 960. I cram that, plus the initial value for x = 1 onto the machine and get cranking.