Sorting with absolute precision
- To: mathgroup at smc.vnet.net
- Subject: [mg34823] Sorting with absolute precision
- From: "DrBob" <majort at cox-internet.com>
- Date: Sat, 8 Jun 2002 05:21:44 -0400 (EDT)
- Reply-to: <drbob at bigfoot.com>
- Sender: owner-wri-mathgroup at wolfram.com
I ran into something that surprised me. I know why it happens, but it took me aback at first, so it may be useful for other newbies to ponder it. If I sort the cosines of some random machine-precision numbers, the results make sense. They're sorted as I expect. angles = Random[] & /@ Range[10] Sort[Cos /@ angles] {0.237688, 0.646417, 0.635763, 0.266813, 0.861474, 0.0729049, 0.112744, \ 0.334724, 0.48266, 0.370323} {0.65132, 0.798247, 0.804619, 0.885763, 0.932211, 0.944501, 0.964616, \ 0.971885, 0.993651, 0.997344} But here's a VERY different situation: angles = Random[Integer, {1, 10}] & /@ Range[10] Sort[Cos /@ angles] Sort[Cos /@ angles] // N Sort[Cos /@ angles // N] {7, 3, 5, 1, 9, 9, 8, 8, 10, 1} {Cos[1], Cos[1], Cos[3], Cos[5], Cos[7], Cos[8], Cos[8], Cos[9], Cos[9], Cos[10]} {0.540302, 0.540302, -0.989992, 0.283662, 0.753902, -0.1455, -0.1455, \ -0.91113, -0.91113, -0.839072} {-0.989992, -0.91113, -0.91113, -0.839072, -0.1455, -0.1455, 0.283662, \ 0.540302, 0.540302, 0.753902} This time the first two sorts sort unevaluated expressions, so the cosines are not in order! The third sort evaluates the cosines first, and sorts them properly, but we've lost precision. If you want the arbitrary-precision cosines properly sorted, do this: Sort[Cos /@ angles, OrderedQ[{N[#1], N[#2]}] &] {Cos[3], Cos[9], Cos[9], Cos[10], Cos[8], Cos[8], Cos[5], Cos[1], Cos[1], Cos[7]} Technically that's not good enough, since lost precision can affect the ordering of elements, but... it's good enough for my purposes. Bobby Treat