Re: Pi day
- To: mathgroup at smc.vnet.net
- Subject: [mg108458] Re: Pi day
- From: Ray Koopman <koopman at sfu.ca>
- Date: Thu, 18 Mar 2010 04:34:12 -0500 (EST)
- References: <hnnk1f$cfe$1@smc.vnet.net>
On Mar 16, 2:46 am, Ray Koopman <koop... at sfu.ca> wrote: > The code I gave can certainly be speeded up, but right now I'm more > concerned about the algorithm. 'hi' is meant to be the smallest value > of the form s[[i]]/s[[j]] that is greater than Pi, and 'lo' is meant > to be the largest value of the form s[[i]]/s[[j]] that is less than > Pi. 'hi' is OK, but I wonder about 'lo'. > > Specifically, potential values of 'lo' with j > k are never checked, > where k is the largest value of j for which s[[-1]]/s[[j]] > Pi. When > the While[j < k, ...] loop exits, we have j = k, s[[i]]/s[[j]] > Pi, > and s[[i-1]]/s[[j]] < Pi. s[[-1]]/s[[k+1]] < Pi, but might it not > also be > the current 'lo'? One more check is necessary. If j > k then s[[i]]/s[[j]] < Pi for all i, so we need to check the largest possible new value for 'lo'. Here is the revised code, compiled. hiloPi = Compile[{}, Module[{s,i,j,k,hi,lo,ijhi,ijlo}, s = (Permutations@Range@9).(10^Range[8,0,-1]); i = j = 1; While[s[[i]]/s[[j]] < Pi, i++]; hi = s[[ i ]]/s[[j]]; ijhi = { i ,j}; lo = s[[i-1]]/s[[j]]; ijlo = {i-1,j}; k = Length@s; While[s[[-1]]/s[[k]] < Pi, k--]; While[j < k, j++; While[s[[i]]/s[[j]] < Pi, i++]; If[s[[ i ]]/s[[j]] < hi, hi = s[[ i ]]/s[[j]]; ijhi = { i ,j}]; If[s[[i-1]]/s[[j]] > lo, lo = s[[i-1]]/s[[j]]; ijlo = {i-1,j}]]; If[s[[-1]]/s[[k+1]] > lo, lo = s[[-1]]/s[[k+1]]; ijlo = {-1,k+1}]; {s[[ijhi]],s[[ijlo]]}]] Timing@hiloPi[] N[Divide@@#-Pi]&/@%[[2]] {1.23 Second,{{429751836,136794258},{467895213,148935672}}} {1.0185541299279066*^-10, -8.499689840846258*^-11}