Compile succeeds and then fails with a simple change.

GROUPS:
 W. Craig Carter 1 Vote The following works just fine: positions = RandomReal[{-200, 200}, {1000, 2}]; example1 = Compile[{{positions, _Real, 2}}, Block[{distanceMat, distanceMatCubed, differenceMat, ret}, differenceMat = Outer[Subtract, N[positions], N[positions], 1] ; distanceMat = Map[#.# &, differenceMat, {2}] + IdentityMatrix[Length[positions]]; distanceMatCubed = distanceMat^3; (*{ Total[-12 differenceMat ( 1-distanceMatCubed)/distanceMat^7], Total[(1-2distanceMatCubed)/distanceMat^6] }*) Total[-12 differenceMat ( 1 - distanceMatCubed)/distanceMat^7] ] ] Timing[example1[positions];] However, this doesn't: example2 = Compile[{{positions, _Real, 2}}, Block[{distanceMat, distanceMatCubed, differenceMat, ret}, differenceMat = Outer[Subtract, N[positions], N[positions], 1] ; distanceMat = Map[#.# &, differenceMat, {2}] + IdentityMatrix[Length[positions]]; distanceMatCubed = distanceMat^3; { Total[-12 differenceMat ( 1 - distanceMatCubed)/distanceMat^7], Total[(1 - 2 distanceMatCubed)/distanceMat^6] } ] ] Timing[example2[positions];] Looking at the CompilePrint, the offending line appears to be:MainEvaluate[ Hold[List][ T(R2)6, T(R1)12]]Where T(R2)6 = Total[ T(R3)11, I12]] and T(R1)12 = Total[ T(R2)11, I12]] appear to be valid results.Perhaps, I need to coerce the final result type... but I am not sure how to do this. Any advice? Thanks, Craig
4 years ago
4 Replies
 btw, you meant to write example[particles] and not example[positions]As for the problem, it seems relating to the list at the end. Simply putting Flatten at the end, removes the error and not it works.  particles = RandomReal[{-200, 200}, {1000, 2}]; example = Compile[{{positions, _Real, 2}}, Block[{distanceMat, distanceMatCubed, differenceMat, ret}, differenceMat = Outer[Subtract, N[positions], N[positions], 1]; distanceMat = Map[#.# &, differenceMat, {2}] + IdentityMatrix[Length[positions]]; distanceMatCubed = distanceMat^3; Flatten@{Total[-12 differenceMat (1 - distanceMatCubed)/distanceMat^7], Total[(1 - 2 distanceMatCubed)/distanceMat^6]} ] ] example[particles]