Tag Info

Hot answers tagged

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


17

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


12

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


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


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


9

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


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


6

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


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}] + ...


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


4

A lot of time is being spent on: For[min = 1, MemberQ[ncols, min], min++]; min Replacing it with: First @ Complement[Range @ NumberOfVertices, ncols] appears to speed things considerably. This appears to be about twice as fast as the original. Can you confirm? GAColor2[adjmatrix_, PopulationSize_Integer : 100, NumberOfGenerations_Integer : 10, ...


4

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


4

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


4

If I understand the problem correctly, sampling l without replacement can be done all at once with RandomSample[l]. It is equivalent to sampling the entire list, past when you would quit, but it does it very quickly. Position tells you how many times it would take to sample v on that particular run. n = 5000; runs = 5; l = Range[n]; k = Table[v = ...


3

Probably the main reason why your calculation is slow is that you're using SetDelayed (:=) which means that the derivatives are calculated again and again every time a quantity such as PreAAA is called. Instead, just replace all those assignments with Set (=) to evaluate the derivatives symbolically once and for all: Clear[l, r, m, Theta, Phi, k]; preAAA = ...


3

Multiple evaluations can often be avoided by using With. You might try something like f = With[{q = Q[FK, ....]}, If[CDF[f, id[is, q, #]] == 0., 0.1, CDF[f,id[is, q, #]]]]&


3

The syntax you are using is incorrect. Try model[{1,2,3}] and notice that it can't be applied to a list. Just change model[data[[All,1]]] to model /@ data[[All,1]]. This will finish in time, but it won't be fast at all (I do not know why). This will be much faster (in place of model /@ data[[All,1]]): model["BestFit"] /. x -> data[[All, 1]]


3

Using Mhad = 0.93827; t = Table[ Tooltip[(MxSq - M^2) x/(1 - x) /. M -> Mhad,"x=" <> ToString[x]], {x, 0, .9, .1}]; With[{s = 50}, p1=Plot[{1/s (s - M^2) (s - MxSq) /. M -> Mhad, t}, {MxSq, Mhad^2,100}, PlotRange -> {{.8, 100}, {.8, 100}}, AspectRatio -> 1, Filling -> {1 -> Axis}, Frame -> True, ...


3

Basically along the lines suggested by Bill Simpson. The equation setup could perhaps be done with more elegance. Still, it's fairly short code. isUnitDistance[graph_] := Module[ {verts, edges, n, coords, p, x, soln}, verts = VertexList[graph]; edges = EdgeList[graph]; n = Length[verts]; verts = verts /. Thread[verts -> Range[n]]; coords = ...


3

Simply move the derivative computation outside the scope of the Manipulate, using either D or Limit. f[x_, y_] = x^3 + 2 y^3; fx[x_, y_] = D[f[x, y], x]; fx[x_, y_] = Limit[(f[x + h, y] - f[x, y])/h, h -> 0]; fy[x_, y_] = D[f[x, y], y]; fy[x_, y_] = Limit[(f[x, y + h] - f[x, y])/h, h -> 0] Manipulate[ x0 = p[[1]]; y0 = p[[2]]; Show[{ Plot3D[{f[x, ...


3

The limits can be calculated analytically one time and then used inside your Manipulate. You can use With to place the final expression where you need them: f[x_, y_] := x^3 + 2*y^3; With[{l1 = Limit[(f[px + h, py] - f[px, py])/h, h -> 0], l2 = Limit[(f[px, py + h] - f[px, py])/h, h -> 0]}, Manipulate[ {px, py} = point; Show[Plot3D[f[x, y], ...


2

Yes, it is stiff -- but the main issue that I see is that the solution goes wild near the TMax that you specify. That's because you need a super-fine spatial grid to accurately represent what happens when the higher order terms finally manifest themselves. It's going to take a lot of time and a lot of memory (MinPoints option), and there's no way around it. ...


2

I do not know how to compute whether a graph is a unit distance graph. However, if you know the name of a graph you can ask Mathematica directly. For example, GraphData["GolombGraph"] GraphData["GolombGraph", "UnitDistance"] As you may know, graphs that Mathematica classifies as unit distance graphs are the following: Cases[{#, GraphData[#, ...


1

Another way to get a speedup is to compile. Your own code with a minimal change would look like : makeRuns = Compile[{{n, _Integer}, {runs, _Integer}}, Module[{k = Array[0 &, runs], v, s, i, l}, Table[{v = RandomInteger[{1, n}]; s = 0; i = 0; l = Range[1, n]; While[s != v, s = RandomChoice[l]; l = DeleteCases[l, s]; ...


1

Before I start, I want to acknowledge that Daniel's answer is faster than mine because mine does not take advantage of the specific form of the energy function. However, the solution with Cellular Automaton seems very cool and works for any energy function so I decided to put it up anyway. CellularAutomaton can take a function as an argument to evaluate on ...


1

[Not an answer, but too big for a comment] An alternative approach is to write it as an integer linear program. Below is code for this, with appropriate post-processing omitted to confuse the weak-minded (starting with the author). n = Length[VertexList[g]]; edges = EdgeList[g]; vars = Array[x, {n, n}]; fvars = Flatten[vars]; tvars = Transpose[vars]; c1 = ...


1

Once can see by using Trace that an apparently simple call is far more complex than you might imagine. Why it is designed this way, and if it needs to be, is an entirely different matter. Be prepared to forcefully terminate Mathematica (or at least Quit[] the kernel) and then run: AstronomicalData["Mercury", {"RightAscension", {2012, 10, 11, 12, 13, ...



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