Floating point and two Lua exercises

1. A quick introduction to maths in Lua

You will have discovered that mathematics in Lua is sometimes "strange", e.g. that very large positive numbers sometimes "overflow" and become negative. This behaviour is slightly different between different versions of Lua. For example,

print(8723648723*92837492834)

gives a negative value in some versions of Lua and 8.0988167580785e+20 in others. What is going on here is this:

Lua, like most programming languages, has separate concepts of "integers" and "real numbers". Both are limited in what they can contain. Integers are exact, but if an integer gets too big strange things can happen such as an expected positive number may be calculated as negative. Real numbers are stored in a special "floating point" format (like on a calculator) with a limited number on decimal places.

If you want to treat a number as a floating point number you can always add ".0" on the end:

print(8723648723.0*92837492834.0)

You can convert by multiplying by 1.0 or adding 0.0.

a = 8723648723
b = 92837492834
print (a * b)
a = a * 1.0
b = b + 0.0
print (a * b)

Integer division is particularly awkward for beginners (it tends to round towards 0 to the nearest integer). If you don't like this convert to floating point with a ".0" somewhere.

Mathematical functions like "sin" and "log" are available in Lua via the math library. We won't need them here, but you can find out about them elsewhere if you like, such as at http://lua-users.org/wiki/MathLibraryTutorial

2. Two Lua exercises

That's all for the introduction to Lua here. If you want to read more serach the web or read the Lua manual. We finish here with two exercises using programming in Lua for students that have made it this far.

A convergent sequence

Define a sequence a n by a 0 = 1 and a n + 1 = 1 + a n a n .

Write a Lua program to calculate the first 20 values of this sequence. (Make sure calculations use floating point.) What do you think the limit is?

Using what you know from real analysis, prove that the limit of this sequence is the number you think it is.

Lua's representation of these numbers is not perfectly accurate, and to get the best approximation to the limit that is possible in Lua it suffices to take a n for some reasonably small n . What n is good enough here?

A series

Define b n = i = 1 n 1 i ( i +1 ) .

Write a Lua program to calculate b n for various values of n . (You will have to ensure that you use floating point.) Calculate the sum exactly as written above.

Now calculate the exact value of the summation. Do this by using partial fractions and making cancellations.

Your exact answer and Lua's answer should be at least nearly the same. (Any small differences will be due to inaccuracies in Lua's floating point numbers.) Check this to confirm that your program is working correctly.