[Edu-sig] Truth values and comparisons
davelist at mac.com
davelist at mac.com
Mon Oct 30 15:23:38 CET 2006
On Monday, October 30, 2006, at 08:30AM, "Arthur" <ajsiegel at optonline.net> wrote:
>Looking for a little education on edu-sig.
>On one hand I am feeling like a big boy, having announced today on the
>vpython list that I think I have adequately accomplished the necessary
>fixes to the vpython C++ code to accomplish compatibility with the newly
>released numpy 1.0, and in a way that I think in the end (it was a
>round-about process for me) is straightforward and unlikely to
>introduce bugs into the existing stable codebase.
>OTOH, I am learning there is some very basic Python I do not understand.
>Now having a vpython that runs against numpy, I am learning about some
>of the changes in the numpy Python API versus that of Numeric and
>numarray. One basic incompatibility is in that the older libraries did
>something to give a result in comparing 2 arrays that numpy backs away
>from - complaining about ambiguity.
>For example, in the vpython faces_heightfield.py demo there is a line:
> >>>normal[i] = vertex_map[tp] and norm( vertex_map[ tp ] )
>which ran fine under Numeric and numarray, and now fails with a message:
>The truth value of an array with more than one element is ambiguous.
>Use a.any() or a.all()
>For the purposes of the exercise assume that both "vertex_map[tp]" and
>"norm( vertex_map[ tp ]"
>each return one dimensional, 3 element numpy arrays. Not exactly true,
>but I think the result would be the same if it were.
>In the original code, what is the "and" doing, and in what way might the
>"any" or "all" built-ins be used to get the result intended by it?
I've not used .any or .all, but having just taught my CS1 students about boolean operators, I was reminded that Python works as the following example describes:
x = a and b
# if both a and b are true, x is assigned b, otherwise x is assigned a
x = 2 and 3 # x is assigned 3
x = 0 and 2 # x is assigned 0
x = a or b
# if a is true, x is assigned a, if a is true, x is assigned a, if a is false and b is true, x is assigned b, if both a and b are false, x is assigned False
You need to determine what should make vertex_map[tp] be true (maybe it is all the values being non-zero or maybe it is just the array being non-empty) and assuming norm is then a single floating point value, if it's non-zero, it is true. And then assign normal[i] the appropriate one.
More information about the Edu-sig