# Tag Info

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

20

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.

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

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

12

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

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

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

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

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

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

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

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

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

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

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

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

6

I think you can do this with Quantile. Being unfamiliar with that I'll show something I think is equivalent using Interpolation. The idea is to give an "inverse" based on your weights, and create a lookup function for random reals between 0 and 1. For example, suppose you want to find random integers from 1 to 10, weighted by inverse of reversing those ...

6

If all you want is to remove a linear trend from the data you don't need all the fancy statistics done by LinearModelFit and a faster alternative is to just use LeastSquares and then use the resulting parameters to remove the trend from the data. (*Generate 150k datapoints with a linear trend*) data = RandomVariate[NormalDistribution[0, 50], {150000, 2}] + ...

6

Since no comment or answer has given as of the time I saw this post, and I don't have enough reputations to leave a comment, let me give a quick answer I used to solve the same kind of problems. I'm sure there must be a better way to do it with Mathematica, so this is just a beginning. To evaluate an N-dimensional integral with a highly oscillatory ...

6

Update: I thought to summarize all results in a small table, to make it easy to see. Thanks for george2079 for adding the C++ and Python results (may be I'll do Java later) results in seconds. Lower is better. Notice that Fortran was run on a virtual machine (VBox). Grid[{ {"Mathematica", "Matlab (elapsed)", Column[{"Fortran", "Virtual machine)"}, ...

5

The ideas mentioned in comments and the prior response seem like good ways to go about this. As for the brute force direct method, for a reliable result you can precompute one part symbolically and handle the rest numerically. ii[y_] = Integrate[ PDF[NormalDistribution[0, 8/1000], x - y]*4 *DiracDelta[1 - x], {x, 0, 11/10}]; firstTry[y_?NumberQ] := ...

5

A slightly modified version of the function ginivalues from @SethChandler's Wolfram demonstration LorenzCurvesAndTheGiniCoefficient gives about 6000x speed-up. Define giniF[dt_List] := With[{sorted = Accumulate[Sort[dt]]}, N@Mean[2 MapThread[#1 - #2 &, {Range[1/Length[dt], 1, 1/Length[dt]], sorted/Last[sorted]}]]] Using the medals dataset: giniF ...

5

I'm not sure you are handling the top and left edges in the way you really want; they work with the second rather than first elements being treated as "middle" twice, with first elements not treated that way at all. Here is code that does not do that, hence gives different results than yours on top and left edges. It is around two orders of magnitude ...

5

In the Manipulate as you wrote it, the InverseFunction has to be re-calculated every time the function x is called. To avoid this, define x with Set instead of SetDelayed: f[x_] := Sqrt[x]; c[x_] := x^2; g[x_] := c'[x]/f'[x]; Clear[x]; Block[{gamma, δ, φ, ρ, mode}, x[gamma_, δ_, φ_, ρ_, mode_] = InverseFunction[g][gamma/(1 - δ*φ*ρ)*mode] ] (* ...

5

Here is another way, which is pretty fast. The number n of sections does not matter as an argument, so it is omitted. f0[x_, m_] := With[{v = Partition[x, m]}, m^2 - Max @ Total[UnitStep[Transpose @ ConstantArray[v, m] - RotateLeft[v]], {2, 3}]] Example 1: x = {1, 16, 3, 6, 20, 5, 13, 14, 2}; f0[x, 3] (* 4 *) Example 2: SeedRandom[1]; x2 = ...

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