Tag Info

Hot answers tagged

27

First let me note that I didn't write PositionIndex, so I can't speak to its internals without doing a bit of digging (which at the moment I do not have time to do). I agree performance could be improved in the case where there are many collisions. Let's quantify how bad the situation is, especially since complexity was mentioned! We'll use the ...


24

Summary We can look at the code of DeleteDuplicatesBy and it turns out it uses GroupBy. The test cases proposed by Mr.Wizard are all handled by some part of the code of DeleteDuplicatesBy. Other parts of this code also seem to have some issues. Most of the members of the *By family of functions seem to have side effects. How DeleteDuplicatesBy works It ...


22

A very simple and straightforward test for square-freeness (and should be reasonably fast) is: squareFreeQ[str_] := StringFreeQ[str, x__ ~~ x__] Testing on your inputs: squareFreeQ["0101"] (* False*) squareFreeQ["0102012021"] (* True *) You can then possibly restrict this further to operate only on certain alphabets using Repeated and Alternatives. ...


21

You are trying to implement Euler-Maruyama simulation method for a 2-stage short-term interest rate model which is given by the following system of SDEs: $$\begin{eqnarray} \mathrm{d} \theta_t &=& -\lambda_\theta \left( \theta_t - \bar\theta\right) \mathrm{d}t + \sigma_\theta \mathrm{d}W_{\theta,t} \\ \mathrm{d} \pi_t &=& ...


17

This is your idea with different functions: FreeQ[Differences@IntegerDigits[n], _?Negative] hmmm.. OrderedQ@IntegerDigits[n] This is in case if sequence is non-descending instead of ascending but OP's functiong gives True for 133.


17

@Simon Woods points out in a comment that: In fact the delay on the initial run is caused by compiling code to provide the Poisson distribution :-) You can look at ImageColorOperationsDumpiImageEffectPoissonNoise to see how it works internally. Now, although PoissonDistribution can't be compiled, there's nothing stopping the use of my own C++ ...


16

Attempting to analyze the performance of this function in the manner that Taliesin Beynon did for PositionIndex I shall use the same tools. The old method that will be compared in all cases below: myDeDupeBy[x_, f_] := GatherBy[x, f][[All, 1]] Speed A BenchmarkPlot of DeleteDuplicatesBy versus myDeDupeBy: Needs["GeneralUtilities`"] BenchmarkPlot[ ...


14

Graphics`Mesh`PolygonIntersection[] is not documented; it builds full polygon triangulations. To handle holes, you can use: PolygonIntersection[a, b, FillingMethod -> "OddEvenRule"] or PolygonIntersection[a, b, FillingMethod -> "WindingRule"] To create the visualization: Graphics`Mesh`MeshInit[]; a = Polygon@RandomReal[1, {100, 2}]; b = ...


13

Sum, like Integrate, does some symbolic processing. For instance, your sum with an indefinite end point n returns a closed-form formula: Sum[i, {i, n}] (* 1/2 n (1 + n) *) ParallelSum will do the actual summation, one term at a time. There is overhead in parallelization. Often a significant bottleneck is the amount of data that has to be transferred ...


13

Let's start by taking a look at the compiled form of one of our queries: Dataset`CompileQuery[Query @ First @ spans] (* Dataset`WithOverrides@*Checked[Slice[205 ;; 313], Identity] *) We can see that the operation is not implemented directly in terms of part. Indeed, there are three components: Dataset`WithOverrides, GeneralUtilities`Checked and ...


13

Nasser gives good standard ControlActive approach. But that by definition looses quality during motion. I just would like to share a trick that avoids that. Most of the time is spent on rendering your bell shape. But it is static. Plane moves but it is simple, so it should not all the time trigger recomputing of static bell shape. You can separate motion of ...


13

Here is a solution based on binary search (compiled). Implementation First, this is a version of a binary search, which would return the position of a maximal number in a list, smaller or equal to yours, and -1 if no such is found: ClearAll[bsminComp]; bsminComp= Compile[ {{lst,_Integer,1},{elem,_Integer}}, ...


11

I hope I see the essence here. You are interested in the convolution of an interpolated function with a Gauss function Your underlying data has regular spacings in x-direction and the convolution with a Gaussian is extremely fast implemented in GaussianFilter for discrete data. Why are you making it so complicated when the only thing you have to do is ...


11

If you need the ultimate speed, the following compiled code will be about 20 - 30 times faster than the elegant string-pattern based solution of @R.M. (but, of course, as many times longer and uglier): With[{part = Compile`GetElement}, squareFreeQLSC = Compile[{{ll, _Integer, 1}}, Module[{res = 0, ctr = 1, sctr = 1, len = 0, start = 0, i = 0}, ...


11

Edit This one is much simpler than those I posted before . And very efficient Timing@StringFreeQ[benchmark, RegularExpression["(.+)\\1"]] Previous posts: Timings done on a VERY slow machine: Timing@Not@StringMatchQ[benchmark, RegularExpression[".*(.{1,1000})\\1(.*)"]] (* -> {0.735, True} *) Edit There is a problem if the repeated string has ...


11

Try this: n = 1000; coeffs = RandomVariate[NormalDistribution[], n]; f[x_] := Sum[coeffs[[k]] Sin[k x]/k, {k, 1, n}]; Plot[Evaluate@f[x], {x, 0, 2. Pi}, PlotPoints -> n, MaxRecursion -> 0, Mesh -> All] // Timing With[{n = 1000}, First@Timing[Table[Evaluate@f[x], {x, 0, 2. Pi, 2. Pi/n}]] ] 2 times as fast as plot. I remembered my own ...


11

This function will be rewritten in C for 10.0.2 and should come down to average-case complexity of $O(n)$ from its current $O(n \log(n))$. Note that the version most users will be bothered to write (and the way we advertized this before in the docpage for DeleteDuplicates) is $O(n^2)$, so most users are probably already winning. In the meantime, my advice ...


11

This seems fast(er): Extract[a, Transpose[{v, Range@Length@v}]] Addendum Mr.Wizard's clean method Diagonal @ a[[v]] has a surprising property for those of us who think that packed arrays rank just below the wheel in the list of inventions for the sake of efficiency. For unpacked arrays a, it uses virtually no extra memory. Example Initialization. ...


10

This has [quadratic, he said] actually perhaps cubic complexity in a worst case (okay, now I'm just confused. More below).. Not the fastest of the lot, but it seems reasonable, or at least not entirely unreasonable. Requires some thought for me to see what I'm doing that keeps it relatively slow. squareFree[wrd_String] := squareFreeC[ToCharacterCode[wrd]] ...


10

A new solution I realized that comparing each and every value in the sections might be inefficient, especially in cases where the sections are long. Instead we need only the relative ordering of these elements from which we can compute the number of Less pairs. Here is my solution: Edit: Ray Koopman provided a greatly improved counting method (applied to ...


10

Actually, it is all about packing. By using RandomReal you an generating packed sub-arrays even if the complete array is not packed (and can't be, due to irregular shape): Map[PackedArrayQ, testList, {2}] // Short {{True,True},{True,True},{True,True},{True,True},{True,True},<<91>>,{True,True}, {True,True},{True,True},{True,True}} Let's ...


9

I will use big and small rather than bigList and smallList, for brevity. As stated by others if you can select the positions at random in the first place this will be faster, e.g.: pos = RandomSample[Range @ Length @ big, 1200]; You can then get the small list with: small = big[[pos]]. To carry out the specific operation you describe the key detail will ...


9

You can get it about 5-6 times faster if you define a separate function (to do Transpose just once): ClearAll[f]; f[x_?NumericQ] = # * UnitStep[First @ #] * UnitStep[Last @ #] & /@ Transpose[{solutionsA[x, a, b], solutionsB[x, a, b]}], and the presence of UnitStep makes Select unnecessary, with visually the same output. You can then ...


9

You've tried to use Fold, which is good, but the spirit of the algorithm is still very "procedural", in that you're not utilizing the Listable properties of certain functions and you're brute-forcing your way through the set of integers. For instance, Mod can take a list as a second argument, Fold[Times, 1, Range@20] is better written as Times @@ Range@20 ...


9

Update Almost ten times faster again, or about 90 times faster than the OP's way (0.069 sec v. 5.46 sec): For the second integral, we can find its derivative with respect to x and then integrate with NDSolve. The derivative of the integral has two components, one from differentiating under the integral sign dxdz1 and one from plugging in the limit of ...


8

Analyze the integrand $f(r)r^2$: {Expand[Numerator[#]], Denominator[#]} & @ (Apart[f[r]][[#]] r^2 // FullSimplify) & /@ Range[3] The result exhibits the integrand as a sum of six fractions whose numerators are in the form $\lambda \exp(2 r \alpha / 3) r^k$ for $k=1,2$ and whose common denominator is in the form $(1 + \mu \exp(4 r \alpha / 3))^2$ ...


8

There are two areas for optimization that I see here. The first, if possible, is to generate all your random data in advance and then access it with an incrementing index, e.g. list[[i++]]. The second is to partially evaluate the definitions of thetaNext and piNext for a given set of parameters. A note: Random has been deprecated for some time now and may ...


8

This is not an answer. It is just a very long comment. Both a simple manually operated drill press and a computer-controlled five-axis omni-mill can drill a hole through a piece of bar stock. And both will do the actual drilling in about the same amount of time. If one hole in one bar is all you want, then you will accomplish the job much faster with the ...


8

A solution which outperforms the currently given answers is the following: You build up the complete expression of your function using Which, so that you have in the end tuned[x_]:=Which[ Positive[Sin[3 x]]&&Positive[Tan[3 x]],{2 Sin[3 x],2 Tan[3 x]}, Positive[Cos[3 x]]&&Positive[-Cot[3 x]],{2 Cos[3 x],-2 Cot[3 x]}, Positive[-Sin[3 ...


8

Bear in mind that I'm not completely sure what you are calculating, here is my 5 cents towards what can help you get a better performance. I haven't benched marked the MATLAB code on my system, but the changes implemented in Mathematica lead to a runtime decrease from 78.036 s down to to 0.171 s. The slowing factors where mainly that you handle a lot of ...



Only top voted, non community-wiki answers of a minimum length are eligible