GiovineItalia / Gadfly.jl

Crafty statistical graphics for Julia.
http://gadflyjl.org/stable/
Other
1.9k stars 250 forks source link

Plotting an array of Float64s gives me an InexactError #545

Open jfhc opened 9 years ago

jfhc commented 9 years ago

This is the code that gave me the problem:

probabilities = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
function Hx(Ph)
    return Ph == 0 || Ph == 1 ? 0 : -1 * ((Ph * log2(Ph)) + ((1-Ph) * log2(1-Ph)))
end
entropies = map(x -> (x, Hx(x)), probabilities)

using Gadfly
plot(x=map(p -> p[1], entropies), y=map(p -> p[2], entropies),  Geom.point, Geom.line,
Guide.xlabel("Probability of heads"), Guide.ylabel("Entropy"), Guide.title("Entropy of coin flip"))

Giving rise to this error:

InexactError()

 in setindex! at /home/juser/.julia/v0.3/DataArrays/src/indexing.jl:189
 in apply_scale_typed! at /home/juser/.julia/v0.3/Gadfly/src/scale.jl:282
 in apply_scale at /home/juser/.julia/v0.3/Gadfly/src/scale.jl:244
 in apply_scales at /home/juser/.julia/v0.3/Gadfly/src/scale.jl:38
 in apply_scales at /home/juser/.julia/v0.3/Gadfly/src/scale.jl:58
 in render at /home/juser/.julia/v0.3/Gadfly/src/Gadfly.jl:650
 in writemime at /home/juser/.julia/v0.3/Gadfly/src/Gadfly.jl:804
 in sprint at iostream.jl:229
 in display_dict at /home/juser/.julia/v0.3/IJulia/src/execute_request.jl:31

Changing the plot to

plot(x=map(p -> p[1], entropies), y=map(p -> float32(p[2]), entropies),  Geom.point, Geom.line,
Guide.xlabel("Probability of heads"), Guide.ylabel("Entropy"), Guide.title("Entropy of coin flip"))

Fixes it fine (i.e. converting the y values to Float32).

This was in iJulia on JuliaBox running Julia v0.3.5.

aviks commented 9 years ago

Simpler replication

plot(x=[0, 2.0, 3.0], y=Real[0,0.1,3.1], Geom.line)

InexactError()

 in setindex! at /home/juser/.julia/v0.3/DataArrays/src/indexing.jl:189
 in apply_scale_typed! at /home/juser/.julia/v0.3/Gadfly/src/scale.jl:282
 in apply_scale at /home/juser/.julia/v0.3/Gadfly/src/scale.jl:244
 in apply_scales at /home/juser/.julia/v0.3/Gadfly/src/scale.jl:38
 in apply_scales at /home/juser/.julia/v0.3/Gadfly/src/scale.jl:58
 in render at /home/juser/.julia/v0.3/Gadfly/src/Gadfly.jl:650
 in writemime at /home/juser/.julia/v0.3/Gadfly/src/Gadfly.jl:804
 in sprint at iostream.jl:229
 in display_dict at /home/juser/.julia/v0.3/IJulia/src/execute_request.jl:31

The input array is an abstract type Real. The first element is an Int, but the subsequent elements are Float64. map actually has found a tight bound, but that confuses Gadfly. Gadfly should probably have a fallback conversion of Number to Float.

aviks commented 9 years ago

@jfhc The Hx function that you have written is not type stable. If you write it as follows, that makes it type stable. This will improve performance of any code that calls Hx, and will make Gadfly plot the result properly.

function Hx(Ph)
    return Ph == 0 || Ph == 1 ? 0.0 : -1 * ((Ph * log2(Ph)) + ((1-Ph) * log2(1-Ph)))
end