Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

julia provide wrong numerical result

When I tried to calculate

julia> -2.3^-7.6
-0.0017818389423254909

But the result given by my calculator is

0.0005506 + 0.001694 i

Just to be safe I tried it again and this time it complains. Why does it not complain when I tried it the first time?

julia> a = -2.3; b = -7.6; a^b
ERROR: DomainError with -2.6:
Exponentiation yielding a complex result requires a complex argument.
Replace x^y with (x+0im)^y, Complex(x)^y, or similar.
Stacktrace:
 [1] throw_exp_domainerror(::Float64) at ./math.jl:35
 [2] ^(::Float64, ::Float64) at ./math.jl:769
 [3] top-level scope at none:0
 [4] eval at ./boot.jl:319 [inlined]
 [5] #85 at /Users/ssiew/.julia/packages/Atom/jodeb/src/repl.jl:129 [inlined]
 [6] with_logstate(::getfield(Main, Symbol("##85#87")),::Base.CoreLogging.LogState) at ./logging.jl:397
 [7] with_logger(::Function, ::Atom.Progress.JunoProgressLogger) at ./logging.jl:493
 [8] top-level scope at /Users/ssiew/.julia/packages/Atom/jodeb/src/repl.jl:128
like image 635
Steven Siew Avatar asked Sep 08 '18 13:09

Steven Siew


1 Answers

This is an order of operations issue. You can see how Julia's parsing that expression:

julia> parse("-2.3^-7.6")
:(-(2.3 ^ -7.6))

and so the reason you don't have any problems is because you're actually taking 2.3 ^ (-7.6), which is 0.0017818389423254909, and then flipping the sign.

Your second approach is equivalent to making sure that the "x" in "x^y" is really negative, or:

julia> parse("(-2.3)^-7.6")
:(-2.3 ^ -7.6)

julia> eval(parse("(-2.3)^-7.6"))
ERROR: DomainError:
Exponentiation yielding a complex result requires a complex argument.
Replace x^y with (x+0im)^y, Complex(x)^y, or similar.
Stacktrace:
 [1] nan_dom_err at ./math.jl:300 [inlined]
 [2] ^(::Float64, ::Float64) at ./math.jl:699
 [3] eval(::Module, ::Any) at ./boot.jl:235
 [4] eval(::Any) at ./boot.jl:234

And if we follow that instruction, we get what you expect:

julia> Complex(-2.3)^-7.6
0.0005506185144176565 + 0.0016946295370871215im
like image 90
DSM Avatar answered Nov 15 '22 07:11

DSM