# Tag Info

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.

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

GraphicsMeshPolygonIntersection[] 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: GraphicsMeshMeshInit[]; 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

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 = CompileGetElement}, 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 ...

10

@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++ ...

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 ...

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

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 ...

7

I'm sorry to say that I do not have a definitive such example. Of course, it's easy to play with the examples provided by the built in package, like OpenCLImplicitRender3D and OpenCLFractalRender3D, but you really need to have quite a high end graphics card for those to work. I am by no means an expert in GPU computing but I have invested some effort ...

7

You can speed things up by using ControlActive on some of the options which slows down things. Like this Manipulate[ ContourPlot3D[{z == 10*x*y*Exp[-x - y], z == k}, {x, 0, 6}, {y, 0, 6}, {z, 0, 3}, ContourStyle -> {Red, Opacity[0.9]}, AxesOrigin -> {0, 0, 0}, Boxed -> False, Mesh -> None, PerformanceGoal -> ControlActive["Speed", ...

7

I get a little more than a 3x increase with this, but it gives a 0/1 output which need to be converted to True/False (can be done at the end) incQ2[n_] := Times @@ UnitStep@Differences@IntegerDigits[n] res2 = Table[incQ2[x], {x, 10^5}] /. {1 -> True, 0 -> False}; // AbsoluteTiming (* {0.550787, Null} *) Boole@res1 == res2 (* True *) For comparison: ...

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