Skip to main content

special functions - Why does N[Re@f] give complex result?


Consider this code:


BlochΚ[κ_, V0_, z_] := 
MathieuC[MathieuCharacteristicA[κ, 2 V0], 2 V0, z/2] +
Sign[κ] I MathieuS[MathieuCharacteristicB[κ, 2 V0],

2 V0, z/2]

Block[{$MaxExtraPrecision = 500, ϵ = 10^-10}, N[Re@BlochΚ[-2 + ϵ, -1, -10]]]
Block[{$MaxExtraPrecision = 1000, ϵ = 10^-20}, N[Re@BlochΚ[-2 + ϵ, -1, -10]]]
Block[{$MaxExtraPrecision = 500, ϵ = 10^-10}, N[Re@BlochΚ[-2 + ϵ, -1, -10]]]

On a fresh kernel I get


(*
-0.484175
-0.993753

-1.38778*10^-16+6.17104*10^-9 I
*)

Why I get complex number at the third time even I used Re explicitly? And why the results are different for the first and third time? Did I made a stupid mistake or what?



Answer



Update: I think this is a numeric precision problem rather than a matter of the behavior of Re.
I don't know if I should leave my original answer below for reference or remove it.


Consider:


expr = MathieuC[MathieuCharacteristicA[-(19999999999/10000000000), -2], -2, 5];


N[expr]
N[expr, 15]
SetPrecision[expr, 15]


-9.85323*10^-16 + 3.39211*10^-8 I

-0.484175231115992

-0.4841752311160


Only the machine precision calculation returns a complex value. I believe that puts this problem in the same class as:



Sorry for the earlier misdirection.


Note: I believe $MaxExtraPrecision has no effect upon a machine precision calculations.




Old, misleading answer


Intending to further illuminate Junho Lee's answer we may consider how Re handles symbolic expressions:


Re[a + b I]



-Im[b] + Re[a]

It performs this replacement whether or not a and b have a numeric equivalent. Therefore:


Re[
MathieuC[MathieuCharacteristicA[-(19999999999/10000000000), -2], -2, 5] +
I MathieuS[MathieuCharacteristicB[-(19999999999/10000000000), -2], -2, 5]
]

Becomes:



Re[MathieuC[MathieuCharacteristicA[-(19999999999/10000000000), -2], -2, 5]] - 
Im[MathieuS[MathieuCharacteristicB[-(19999999999/10000000000), -2], -2, 5]]

And:


Re[MathieuC[MathieuCharacteristicA[-(19999999999/10000000000), -2], -2, 5]]


MathieuC[MathieuCharacteristicA[-(19999999999/10000000000), -2], -2, 5]

Im[MathieuS[MathieuCharacteristicB[-(19999999999/10000000000), -2], -2, 5]]



0

In some manner Re did its job, nevertheless this symbolic expression has a complex numeric value.


If you want a function that operates only on explicit numbers you might use:


re[x_?NumberQ] := Re[x]

Now re will remain unevaluated until its argument is expressly a number:


re[Pi + 4 I]



re[4 I + π]

However N goes inside as re does not have NHoldFirst etc. therefore:


re[Pi + 4 I] // N


3.14159


Comments