Skip to main content

core language - Implementing key-value associations in Mathematica 9 with inexact numbers for keys


I'm not sure of what type of problem my issue falls into, so I haven't been able to search forums with any success. If this has already been solved then my apologies!


Essentially I'm trying to set a list equal to a calculated value then call that list back.


-15*0.1 + 6*0.1

(* -0.9 *)


-15*0.1 + 6*0.1 == -0.9

(* True *)

a[-15*0.1 + 6*0.1] = 5

(* 5 *)

a[-0.9]


(* a[-0.9] *)

a[-0.8999999999999999`]

(* 5 *)

I've reset Mathematica 9.0.1.0 according to this guide http://support.wolfram.com/kb/3274 to no avail.



Answer



It would seem from the title that the OP is asking not only why the scheme does not work but also how to implement it. Three solutions, each with drawbacks, are given below.


An obstruction



Others have given an explanation why it doesn't work. I would add that it is also pointed out in the documentation for Equal in the Details section and under Possible Issues that the tolerance for Equal in comparing approximate machine numbers is the last seven bits ($MachineEpsilon affects the last bit in 1.):


1. == 1. + 2^6 $MachineEpsilon
1. == 1. + (2^6 + 1) $MachineEpsilon
(*
True
False
*)

The solution to the OP's problem would be to create a mapping key from machine reals to a set of keys satifying the condition that x == y if, and only if, MatchQ[key[x], key[y]] returns true. But I don't think this is possible. There is no way to assign keys to 1., 1.000000000000014, and 1.000000000000015 to meet the condition, since Equal is not transitive:


1.000000000000014 == 1.

1.000000000000015 == 1.
1.000000000000014 == 1.000000000000015
(*
True
False
True
*)

Near solutions


Requirements: The first two solutions depend on the keys being far apart, enough so that Equal is effectively transitive, and the third does not have this requirement. The first one is somewhat slow but easy to understand. The second is fairly quick but has a potentially serious drawback. For the third, the keys do not have to be far apart but all the data needs to be known at once; to add key/value pairs requires recomputing the whole dictionary. It's somewhat fast to recompute, so if this not done very often, it may be a practical solution.



Note well, though, that in any solution, the potential for round-off error to land a number closer to the wrong key is always a concern.


A good-enough solution - Use Condition and Equal


Here is the easiest solution to understand:


a[x_ /; x == key] = value

For a dictionary of 10^4 elements,


SeedRandom[1];
keys = RandomReal[1, 10^4];
values = RandomInteger[{1, 10}, {10^4, 2}];


it takes over a minute to initialize all the values for a. In accessing a[x], Mathematica basically does a linear search through the 10^4 downvalues of a. Here's the timing for the last one, which is about the same time it takes to look up a key for which a is undefined:


a[keys[[-1]]] // AbsoluteTiming
(*
{0.006379, {10, 8}}
*)

On average, assuming only defined values are looked up, the expected time would be half that or 0.00319 sec. If a[x] is executed for a lot of undefined keys x, then the average time would increase.


Faster - Round off the keys


One can use Round (or Floor etc.) to map a real x onto a key. The function associated with the option value for "KeyFunction" does this. One potential issue is that a function such as Round segments the real numbers into intervals. Two input data may be very close but on opposite sides of the boundary.


ClearAll[setupdict, associate];

Options[setupdict] = {
Tolerance -> 2^6 $MachineEpsilon,
"KeyFunction" -> Function[{x, tol}, Round[x, 2^Ceiling@Log2[Abs[x] tol]]]};
setupdict[a_Symbol, OptionsPattern[]] := (
ClearAll[a];
Options[a] = {
Tolerance -> OptionValue[Tolerance],
"KeyFunction" -> (Evaluate[OptionValue["KeyFunction"][#, OptionValue[Tolerance]]] &)};
With[{keyfn = OptionValue[a, "KeyFunction"]},
a[x_?NumericQ] := With[{key = keyfn[x]},

a[key] /; ! MatchQ[x, key]
]
]
);
associate[a_, x_?NumericQ, value_] :=
With[{key = OptionValue[a, "KeyFunction"][x]},
a[key] = value
]

It's much faster on 10^4 elements.



setupdict[a];
MapThread[
associate[a, ##] &,
{keys, values}
]; // AbsoluteTiming

{0.142925, Null}

The access time is roughly constant and the average time is low:


First@AbsoluteTiming[a /@ keys;] / 10^4

(*
0.0000119601
*)

OP's example:


setupdict[a];
associate[a, -15*0.1 + 6*0.1, {"my", "list"}]
(*
{"my", "list"}
*)


a[-0.9]
(*
{"my", "list"}
*)

However, some day a key being on the boundary of Round will cause an error.


Faster, if all data is known - Use Nearest


If all the data is known at the beginning, one can use Nearest to construct a look-up function is that is very fast.


ClearAll[setupdict];

Options[setupdict] = {Tolerance -> 2^6 $MachineEpsilon};
setupdict[a_Symbol, data_, OptionsPattern[]] := (
ClearAll[a];
Options[a] = {Tolerance -> OptionValue[Tolerance],
"Dictionary" -> Nearest[data]};
With[{dictfn = OptionValue[a, "Dictionary"]},
a[x_?NumericQ] := dictfn[x, {1, OptionValue[Tolerance]}]
]
);


Example


ClearAll[a];
setupdict[a, keys -> values]; // AbsoluteTiming
(*
{0.011551, Null}
*)

Example


a[keys[[1]]]
a[keys[[1]] + 2^6 $MachineEpsilon]

(*
{{6, 8}}
{{6, 8}}
*)

Undefined at 0.1 returns an empty list:


a[0.1]
(*
{}
*)


Timing -- quite fast:


First@AbsoluteTiming[a /@ keys] / 10^4
(*
5.1667*10^-6
*)

Comments

Popular posts from this blog

plotting - Filling between two spheres in SphericalPlot3D

Manipulate[ SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi}, Mesh -> None, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], {n, 0, 1}] I cant' seem to be able to make a filling between two spheres. I've already tried the obvious Filling -> {1 -> {2}} but Mathematica doesn't seem to like that option. Is there any easy way around this or ... Answer There is no built-in filling in SphericalPlot3D . One option is to use ParametricPlot3D to draw the surfaces between the two shells: Manipulate[ Show[SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi}, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], ParametricPlot3D[{ r {Sin[t] Cos[1.5 Pi], Sin[t] Sin[1.5 Pi], Cos[t]}, r {Sin[t] Cos[0 Pi], Sin[t] Sin[0 Pi], Cos[t]}}, {r, 1, 2 - n}, {t, 0, Pi}, PlotStyle -> Yellow, Mesh -> {2, 15}]], {n, 0, 1}]

plotting - Plot 4D data with color as 4th dimension

I have a list of 4D data (x position, y position, amplitude, wavelength). I want to plot x, y, and amplitude on a 3D plot and have the color of the points correspond to the wavelength. I have seen many examples using functions to define color but my wavelength cannot be expressed by an analytic function. Is there a simple way to do this? Answer Here a another possible way to visualize 4D data: data = Flatten[Table[{x, y, x^2 + y^2, Sin[x - y]}, {x, -Pi, Pi,Pi/10}, {y,-Pi,Pi, Pi/10}], 1]; You can use the function Point along with VertexColors . Now the points are places using the first three elements and the color is determined by the fourth. In this case I used Hue, but you can use whatever you prefer. Graphics3D[ Point[data[[All, 1 ;; 3]], VertexColors -> Hue /@ data[[All, 4]]], Axes -> True, BoxRatios -> {1, 1, 1/GoldenRatio}]

plotting - Mathematica: 3D plot based on combined 2D graphs

I have several sigmoidal fits to 3 different datasets, with mean fit predictions plus the 95% confidence limits (not symmetrical around the mean) and the actual data. I would now like to show these different 2D plots projected in 3D as in but then using proper perspective. In the link here they give some solutions to combine the plots using isometric perspective, but I would like to use proper 3 point perspective. Any thoughts? Also any way to show the mean points per time point for each series plus or minus the standard error on the mean would be cool too, either using points+vertical bars, or using spheres plus tubes. Below are some test data and the fit function I am using. Note that I am working on a logit(proportion) scale and that the final vertical scale is Log10(percentage). (* some test data *) data = Table[Null, {i, 4}]; data[[1]] = {{1, -5.8}, {2, -5.4}, {3, -0.8}, {4, -0.2}, {5, 4.6}, {1, -6.4}, {2, -5.6}, {3, -0.7}, {4, 0.04}, {5, 1.0}, {1, -6.8}, {2, -4.7}, {3, -1.