Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- SeedRandom[1];
- data = RandomReal[1, 10]
- (*
- {0.817389, 0.11142, 0.789526, 0.187803, 0.241361,
- 0.0657388, 0.542247, 0.231155, 0.396006, 0.700474}
- *)
- nf = Evaluate@ Interpolation[Transpose@{-data, data}, InterpolationOrder -> 0,
- "ExtrapolationHandler" -> {With[{m = -Max[data]},
- Piecewise[{{-m, # < m}}, Indeterminate] &],
- "WarningMessage" -> False}
- ][-#] &;
- Plot[nf[x], {x, -0.5, 1.5},
- Epilog -> {Red, PointSize@Medium, Point[Transpose@{data, data}]}]
- SeedRandom[1];
- data = RandomReal[1, 1000000];
- nf = Evaluate@ Interpolation[Transpose@{-data, data}, InterpolationOrder -> 0,
- "ExtrapolationHandler" -> {With[{m = -Max[data]},
- Piecewise[{{-m, # < m}}, Indeterminate] &],
- "WarningMessage" -> False}
- ][-#] &; // RepeatedTiming
- nf /@ RandomReal[1, 1000]; // RepeatedTiming
- (*
- {1.43, Null}
- {0.0043, Null}
- *)
- (* Sascha's distance function dist[] *)
- nf2 = Nearest[data, DistanceFunction -> dist]; // RepeatedTiming
- nf2 /@ RandomReal[1, 2]; // RepeatedTiming
- (*
- {0.000015, Null}
- {4.4, Null}
- *)
- Length@data 1000 10000 100000 1000000
- nf2/nf 700 7000 60000 600000
- dist[u_, x_] := 1000000 (* some big number *) /; x > u
- dist[u_, x_] := Abs[u - x]
- Nearest[{1, 2, 2.9, 3, 4} , 2.99, DistanceFunction -> dist]
- (* 2.9 *)
- findL[x_, val_] := Max[Select[x, # < val &]];
- Plot[findL[x, t], {t, 0, 1}]
- fun[c_, lst_] :=
- Reap[Sow[#, Sign[# - c]] & /@ lst, -1, Last[Sort@#2] &][[-1, 1]]
- pts = {0.817389, 0.11142, 0.789526, 0.187803, 0.241361, 0.0657388,
- 0.542247, 0.231155, 0.396006, 0.700474};
- Plot[Quiet@fun[x, pts], {x, 0, 1.5},
- Epilog -> {Red, PointSize@Medium, Point[Transpose@{pts, pts}]}]
- LeftValue[s_] := LeftValueFunction[s, Nearest[s -> "Index"]]
- LeftValue[s_, list_] := LeftValue[s][list]
- LeftValueFunction[s_, nf_][n_] := First @ LeftValueFunction[s, nf][{n}]
- LeftValueFunction[s_,nf_][list_List] := With[
- {n=nf[list][[All,1]]},
- s[[n - UnitStep[s[[n]]-list] ]]
- ]
- SeedRandom[1];
- data = Sort @ RandomReal[1, 10^6];
- nf = Evaluate @ Interpolation[
- Transpose@{-data,data},
- InterpolationOrder->0,
- "ExtrapolationHandler"->{With[{m=-Max[data]},Piecewise[{{-m,#<m}},Indeterminate]&],
- "WarningMessage"->False}
- ][-#]&; //RepeatedTiming
- lvf = LeftValue[data]; //RepeatedTiming
- testdata = RandomReal[1, 10^3];
- r1 = nf /@ testdata; //RepeatedTiming
- r2 = lvf[testdata]; //RepeatedTiming
- r1 === r2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement