[Tutor] math question

Alan Gauld alan.gauld at blueyonder.co.uk
Fri Apr 23 16:41:34 EDT 2004


> tutorial. I understand that the sqrt(2) can't be written as an exact
> value. But the sqrt(2)^2 certainly can be written in an exact value.

No it can't. The mathematically correct result can be but not
the evaluation of the expression. Thats because to evaluate
the expression Python must work out each factor.

In other words, Python knows how to do arithmetic it doesn't
know how to do math.

> seems strange to me (I'm no mathematician and I suspect
> this is a philosophy question rather than a Python question)
> that the language can't figure this out

Python is just a program like any other. Sit down and try to
figure out how you would write that kind of knowledge into
a python program. Then try to figure out how to write it
such that it didn't slow down arith,metic operations to a crawl.

> should see the code and know a difference between adding
> .33 + .33 + .333 and 1/3 + 1/3 + 1/3

The only way the computer can do that is to parse the values,
apply some expert system rules:

If the inverse of a number, x, is added to itself x times
then the result is x.

Now try writing a program to implement that one rule.
Now extend it to cover:

A) If a number, x, has its square root multiplied by its square
   root, anywhere within an expression, substitute x for the result.

B) If the square root of a number, x, is raised to the power 2 return
x.

Check your solution caters for

sqrt(2) * sqrt(2) => 2
sqrt(2) * 3 * sqrt(2) => 2*3 = 6

Now extend it for the zillions of other "obvious" mathematical
rules, (and don't forget to keep the performance real snappy
for number crunching apps)

You'll find it is much easier (and faster) to just evaluate
each term as you come to it (taking account of precedence
and parentheses etc) and produce a final result that way.

> hard time explaining to my daughter when I was helping her
> with a math/geometry problem and showed her how to use the
> Python shell as a kind of calculator

This is not a Python issue its a binary storage issue...
But if you *print* the results (which uses the str() function)
instead of relying on the Python repr() function you should
find it all looks ok:

>>> from math import sqrt
>>> print sqrt(2) * sqrt(2)
2.0
>>> sqrt(2) * sqrt(2)
2.0000000000000004

See the difference?
(This is one reason I use print in all the examples in my online
tutor despite the extra typing - it mostly avoids revealing these
nasty issues early on!)

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list