New answers tagged

0

I offer the following based on Monte Carlo integration, but trying to make use of the facilities Mathematica provides: weights = {2/3, 1/3}; means = {-3, 2}; sd = Sqrt[2]; distributions = NormalDistribution[#, sd] & /@ means; fdist = MixtureDistribution[weights, distributions]; qdist1 = TransformedDistribution[Log[PDF[fdist, f]], Distributed[f, ...


0

Here is a solution via the LibraryLink technique: First, let us make a comparison between BezierNonzeroBasis[n, u] and BernsteinBasis[n, Range[0, n], u] Do[BezierNonzeroBasis[10, 0.1], {10000}] // AbsoluteTiming Do[BernsteinBasis[10, Range[0, 10], 0.1], {10000}] // AbsoluteTiming BezierNonzeroBasis[10000, 0.1]; // AbsoluteTiming BernsteinBasis[10000, ...


1

Association/<||> objects are Atomic and thus unmatchable before 10.4 AtomQ@Association[] yields True. This is confusing because it is not stated anywhere in the manual. For example tutorial/BasicObjects#15871 claims that only numbers (including complex ones), Strings and Symbols are atomic objects. guide/AtomicElementsOfExpressions does not mention ...


2

In general one should not expect to obtain a general symbolic solution (a function x[a,b]) to the given equation since there are two independent variables, see e.g. Solve symbolically a transcendental trigonometric equation and plot its solutions for certain aspects regarding transcendental equations. To get an idea how the solution depends on parameters a ...


2

Perhaps this! It works if you only need the plot and not the values, or the function. That would require more work. ContourPlot3D[ Evaluate[-x + (Log[f2[x]] - Log[f1[x]] + Log[b] - Log[a])/((1 - a) + (1 - 1/f1[x]) - (1 - b) + (1 - 1/f2[x]))] , {a, 0, 1}, {b, 0, 1}, {x, 0, 1} , AxesLabel -> {"a", "b", "x"} , Contours -> {0} , Mesh -> None ...


23

Short answer The local variables of the form varname$... are used by the system, and it is unwise to use symbols with such names as local variables. With, like many other lexical scoping constructs, performs excessive renamings, often even in cases where it isn't strictly necessary. This probably has to do with efficiency - full analysis may be more costly....


10

There is also a newer package, HolonomicFunctions, that has an implementation of Chyzak's generalization of Zeilberger's algorithm. To perform the desired task, use the following commands: smnd = Simplify[ G /. HoldPattern[HypergeometricPFQ[pl_List, ql_List, x_]] :> (Times @@ (Pochhammer[#, k] & /@ pl)) / (Times @@ (Pochhammer[#, k] & /@ ql)...


3

Perhaps you need to define MTensor for variable left and right. The modified code is: #include "WolframLibrary.h" DLLEXPORT int NonzeroBasis(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res) { /*define the argument-varible*/ mreal saved; mint i, p; mreal u; MTensor tensor_U; mreal *U; /*-------------...


2

Is this a "standard" Manipulate which will not grow larger? Ok, use one of already posted answers. Here is an alternative in case where Manipulate is supposed to be generated from a package function or is a part of a bigger code. ClearAll["Test`*"]; BeginPackage["Test`"] myManipulate::usage = "myManipulate[] generates a demo Manipulate"; Begin["`...


12

I appear to be in the minority but I never write big blocks of Mathematica code, it's just too difficult to read. The way I look at it you have to consider how a reader will understand your app. So I make the main block very small, like this: Manipulate[ Row[{ vectorPlotAndTrajectory[y0, b], Show[fy, position[y0, b]] }] , {b, -7.99, 8} , {{y0, 2}...


7

Here is the way it would look if it were my code.My formatting style is much the same as Szabolcs' (including replacing your grid with a column), but I don't like his dangling ], and you won't see those. Also, I always start control specifications on a new line, and I mostly start option specifications on a new line, too. Note: I have redefined ϕ to ...


13

Personally, I use lots of newlines and let the Front End indent. There doesn't seem to be anything special in your code, other than a lot of nesting that is in fact necessary in this case. You were using Grid incorrectly. Grid[a,b] is wrong. Grid[{{a,b}}] or Grid[{{a},{b}}] are correct. I guess you wanted Column[{a,b}], so I changed that. Using Text ...


17

Description In software engineering, it is a good practice to comment your code. I would advise you to utilise comments to partition your code in a following way. Additionally, if you have ever worked with any other programming languages, you could employ indentation. Alternatively, you could modularize your application as to develop it in smaller, more ...


16

Update: The very likely reason for the garbled error messages is that you have a Chinese version of Visual Studio printing errors in Chinese, and there is a mismatch in the character encoding of these messages and how Mathematica tried to interpret them. CreateLibrary has two very useful options: "ShellCommandFunction" and "ShellOutputFunction". Set ...


8

For me (Windows 10) I get a readable error message like So I add mint saved;. Compiling again I get which leads me to change your MArgument_setReal(Res,tensor_N); to MArgument_setMTensor(Res,tensor_N); and then things work. BTW: I use Needs["CCompilerDriver`"]; srccode=" #include \"WolframLibrary.h\" DLLEXPORT int NonzeroBasis(WolframLibraryData ...


5

This is a form of memoization by dynamically defining a Pattern with the results of the executed Expression as clarified by @ciao. The standard form is documented in Functions that remember values they have found and looks like: f[x_]:=f[x]=rhs So as an example: f[x_] := f[x] = f[x - 1] + f[x - 2] behaves the same as i:f[x_] := i = f[x - 1] + f[x - ...


11

Well, facinating question! Code first: Clear["`*"]; n = 5; steps = 1000; dir = {{0, 0}, {1, 0}, {0, 1}}; start = FromDigits[#, 2] & /@ Transpose@Append[RandomChoice[dir, n - 1], RandomInteger[1, 2]]; move[pt_] :=With[{c = RandomChoice@Pick[-dir, BitAnd @@ (# + pt) & /@ -dir, 0]}, pt + c +RandomChoice@DeleteCases[dir, -c]]; move[{2^n, 0}] := {2^n -...


2

I'm a beginner, and I find it interesting to explore the documentation. Some of the commands I've read about have given me interesting ideas for programs. Also, I'm not sure if this has been mentioned, but the Wolfram Demonstrations Project has a bunch of amazing programs you can play with and download the code from.


4

Use memoization. See here for a description of the memoization in general, and here for its Mathematica implementation. This will avoid having to recalculate all the previous values to determine the next one: Clear[x, T, a, b] T[x_] := T[x] = Piecewise[{{1 - x, 0 <= x < 1/7}, {(x + 6)/7, 1/7 <= x <= 1}}] a[n_] := a[n] = n/(n + 5)^5 b[n_] := b[n] ...


3

The following code will help: cc = ConnectedComponents@g; pts = Map[{#, PropertyValue[{g, #}, VertexCoordinates]} &, cc, {2}]; pre = First@MinimalBy[#, Last] & /@ Apply[{#1[[1]] <-> #2[[1]], Norm[#1[[2]] - #2[[2]]]} &, Tuples /@ Subsets[pts, {2}], {2}]; spt = EdgeList@ FindSpanningTree[ CompleteGraph[Length@cc, EdgeWeight -...


5

Fourier transforms do not return the expected result Many users know a particular definition of the Fourier transform. When Mathematica returns an unexpected result and users cannot comprehend what is happening, often it is because Mathematica is using a different definition. In particular, this is the general definition of a transform pair: $$ F(\omega) = ...


1

Here is yet another version fl[x0_] := Cases[Range[x0], y_ /; Mod[x0, y] == 0] On my computer my version is slightly faster than everything else offered so far. In particular, I get the following AbsoluteTiming results on fl[10000000]: "Cases": 9.4 sec "Select": 9.8 sec "Table": 10.8 sec "AppendTo": 15.5 sec "Sow": 15.6 sec Added: Using Divisible[x0,...


2

Another approach is to use Table combined with Nothing which is only available in version 10.2 or later. f[x0_] := Table[If[Mod[x0, x] == 0, x, Nothing], {x, 1, x0}] and then fl[10] (* {1, 2, 5, 10} *) I found this to be slightly faster than using Select or the Sow and Reap approach.


2

Use of "Sow" and "Reap" allow a simple modification of the existing code. E.g. fl[x0_] := Module[{x = 1}, While[x <= x0, If[Mod[x0, x] == 0, Sow[x]]; x++]] and Reap[fl[12]] returns {Null, {{1, 2, 3, 4, 6, 12}}}


7

When you're processing an element at a time using procedural constructs like Module, While, If, and Print in Mathematica, it's usually a sign that you're fighting the language rather than using it. It's much easier and more concise to use functional constructs that work on arrays: fl[x0_] := Select[Range[x0], Mod[x0, #] == 0 &]


1

I'm sure there are a lot of ways to generate random functions. Here's one: a := RandomChoice[{Times, Plus}] @@ (RandomChoice[{Sqrt, Identity, Power}] /@ (RandomSample[{x, y, z}, 3] RandomInteger[{1, 5}, 3])^RandomInteger[{-3, 3}, 3]); To make a matrix of such functions: Table[a, 3, 3] // MatrixForm Of course the output is different each time. ...


5

Preamble Leonid's method is new to me and quite interesting. I expect that as with most of his methods it is well reasoned and has advantages that are not immediately apparent. Nevertheless I also find value in alternative methods, so here is one of mine. I shall use his example code so that these methods may be compared directly. Boilerplate General::...


12

Implementation This is indeed an important problem. It is usually best to have a separate function testing various options. Here is the solution I propose: a wrapper that would factor out the testing functionality from the main function. Here is the code: ClearAll[OptionCheck]; OptionCheck::invldopt = "Option `1` for function `2` received invalid value `3`"...


2

It was clarified in comments that expressions are supposed to be read into Mathematica from a text file. To achieve what OP wants one can read the file as list of held expressions, perform appropriate replacements, then release hold. If we have a test.txt file with following contents: a * b * c * d a^dag We can read it in following way: ReadList["test....



Top 50 recent answers are included