I came across this strange problem:
dd = Compile[{}, Abs[(10^-200 + 10^-200 I)/(10^-200 + I 10^-200)]^2,
CompilationTarget -> "C"]
dd[]
CompiledFunction::cfne: Numerical error encountered; proceeding with uncompiled evaluation. >>
1
It is same with 10^-100, but these exponents cannot be out of bound with 64bit Visual Studio. What's the problem?
Here is the full code, with the corrected power, which still fails:
f =
Compile[{{σt, _Real, 1}, {sρ, _Complex, 1}, {dt, _Real, 1},
{x, _Real}, {nnt, _Integer}},
Module[{kz = 1/2 x, σ = σt, d = dt, i, kp, c, β, r, k, ρ = sρ * 10^-6, nn = nnt},
kp = kz + 0. I;
k = Sqrt[kz^2 - 4 π (ρ[[2]] - ρ[[1]])];
r = (kp - k)/(kp + k) E^(-2 kp k σ[[1]]^2);
c = {{1 + 0. I, r }, {r , 1 + 0.}};
kp = k;
For[i = 2, i < 2 nn + 2, i++,
If[EvenQ[i],
k = Sqrt[kz^2 - 4 π (ρ[[3]] - ρ[[1]])];
r = (kp - k)/(kp + k) E^(-2 kp k σ[[2]]^2);
β = I kp d[[1]],
k = Sqrt[kz^2 - 4 π (ρ[[2]] - ρ[[1]])];
r = (kp - k)/(kp + k) E^(-2 kp k σ[[3]]^2);
β = I kp d[[2]]
];
c = c.{{E^β, r E^β}, {r E^-β, E^-β}};
(*previous k*)
kp = k
];
Abs[(c[[2, 1]] + 1*^-100 + I 1*^-200 )/(c[[1, 1]] + 1*^-100 + I 1*^-200)]^2]
, CompilationTarget -> "C"]
f[{0, 0, 0}, {0, 24, 5}, {6, 4}, 0.025, 1000]
CompiledFunction::cfne: Numerical error encountered; proceeding with uncompiled evaluation. >>
1.00000000000000
Update: I think what is happening is that the matrix c
starts having components too large and at this point it fails. Giving a small imaginary component to \rho
helps and the failure comes only at higher values of nnt. I assume this can't be fixed unless I put conditionals to handle the big values of c
but this would defeat the purpose of compiling.
In[67]:= AbsoluteTiming@
f[{0, 0, 0}, {0, 24 + 47 I, 5 + 47 I}, {6, 4}, 0.025, 1000]
Out[67]= {0., 0.296593}
Compile
gives two orders of magintude increase in speed!
Compile[{}, Module[{x = 10^10}, Floor[x]]][]
, (or 10^whatever for your machine arch.) then understand why... $\endgroup$1.*^-200
instead. $\endgroup$CompilePrint[]
just has one instruction, namelyReturn
... $\endgroup$$MinMachineNumber
and$MaxMachineNumber
… $\endgroup$