New answers tagged programming
7
Nice answer by Mohsen, +1. I am continually impressed by the quality of the J/Link and .NET/Link expertise on this site. I have a couple remarks and then an example program.
The question asked about some general tips for getting started with J/Link. This GraphStream library provides a perfect example for the typical workflow of a J/Link project. The ...
4
What the @#%^&*?! do all those funny signs mean?
It seems questions arise about the meaning of the basic operators, and I hope it will prove useful to have a sort of index for them. It would be nice to have them organized by sign instead of topic, but one can use the find/search feature of a browser to locate an operator in the list.
Below are links to ...
8
I am writing this answer for a person who is familiar with Mathematica and has a good understanding of computer programming, but not so familiar with Java programming language.
Using GraphStream is not so different from using any other Java library. You need to download the GraphStream core files from here and extract it.
gs-core-1.1.2.jar is the only file ...
1
A couple of brute force methods:
Example: $2x^2-3y^2=15$ -- there are 7 solutions up to $x,y=5\,000$.
First method.
(lim = 5*10^3;
c = Tuples[Range[lim], 2];
(sols = Pick[c, c^2 .{2, -3} - 15, 0])) // Timing
{2.058927,
{{3, 1}, {9, 7}, {21, 17}, {87, 71}, {207, 169}, {861, 703}, {2049, 1673}}}
Length[sols]
7
Much faster than Select:
(c = ...
0
You can work this out from the comments to your question, but it's good also to have a full answer.
You can select elements of a list which fulfill a particular requirement using the following syntax as an example:
m = 3;
n = 2;
c = Tuples[Range[m], n]
Select[c, #[[1]]^2 + 2 #[[2]]^2 == 9 &]
The second argument in Select is your criterion and ...
0
No, this is not a bug. The hypothesis that Mathematica remembers if an expression has been evaluated turns out to be true. To see this, compare
Trace[{1, 2, oki}, TraceOriginal -> True]
-> {{1,2,oki},{List},{1},{2},{oki},{1,2,oki}}
and
With[
{expr = {1, 2, oki}},
(*ClearSystemCache[];*)
Trace[expr, TraceOriginal -> True]
]
-> {1, 2, oki}
...
1
Say for $n=1$, you have defined f[{i1}] as your first experiment. For $n=2$, your experiments are defined by f[{i1,i2}], for $n=3$ the experiments are defined by f[{i1,i2,i3}] and etc, with the idea that you wish to allow $n$ such experiments. If you structure your experiments this way, then you can create a list of all experiments by
m = 3; n = 3; c = ...
3
Following belisarius' suggestion you might use something like:
SetAttributes[f, HoldFirst]
f[body_, n_Integer?Positive, m__:3] := Block[{a},
Do[body, ##] & @@ Thread[{Array[a, n], m}]
]
Use:
f[Print[a[1], a[2], a[3]], 3]
f[Print[a[1], a[2]], 2, 4]
f[Print[a[1], a[2]], 2, 5, 7]
How are parameters evaluated for a Plot in Manipulate
The second ...
4
Not quite tested
embeddedNotebookForm /:
MakeBoxes[embeddedNotebookForm[nb : Notebook[cells_List, ___]],
StandardForm] :=
MakeBoxes@
DocumentNotebook[{TextCell@"tag"}] /. {{{Cell["tag"]}} :>
Block[{}, List /@ cells /; True], _Notebook | _DocumentNotebook :>
nb}
So you would do Notebook[...]//embeddedNotebookForm
1
I don't know if it will be possible to produce the Cell dingbat et al, as those don't appear on inline cells. However, you can at least get the formatting of your Cell expression by preventing it from being converted to Box form (doubly, making it inert).
Here is a practical example:
myPrintTemp[expr_Cell] :=
Internal`InheritedBlock[{MakeBoxes},
...
4
As Murray noted, you must have made an error calculating the attraction point:
1/2 (1 - Sqrt[1 + 12 μ]) /. μ -> 0.2
-0.4219544457
Trying a point close to this with your code (Please, please, never provide code again as a bitmap. Typing this is no fun.)
cobweb::usage =
"cobweb[f,x0,nmax,ndrop] produces a cobweb plot for the recursive
...
1
If you are using Mathematica version 9, the best approach is probably to use the new symbolic tensor functionality as suggested by zentient.
However for this problem it may be sufficient to explicitly specify a rule to convert expressions like Norm[-q] into Norm[q]:
myform = Expand[# /. Norm[-x_ + y_.] :> Norm[x - y]] &;
(F2s[q, k1]*F2s[-q, k2]) // ...
6
Using defaults values _. (for multiplication it is 1) works:
{Sinh[3 Q] + Sinh[Q]} /. Sinh[a_. Q] -> (x^a - x^-a)/2
1
I'm still not sure what you're aiming for but if you have been instructed to use Thread perhaps this will help:
eqn = (3/y^4 == 3/x^4 + a/(x + 2 y)^4) /. y -> r x;
Thread[eqn * (r^4 x^4), Equal]
3 == r^4 x^4 (3/x^4 + a/(x + 2 r x)^4)
This merely demonstrates using Thread to apply an operation to both sides of the equation at once.
Or, seeing your ...
3
You can find the roots of your system:
Roots[x^2 - x - 3 μ == 0, x]
which gives
x == 1/2 (1 - Sqrt[1 + 12 μ]) || x == 1/2 (1 + Sqrt[1 + 12 μ])
Indeed these are the two values you found. For stability, you are asking when the derivative of $x^2-3 \mu$ evaluated at the roots is less than 1. Since the derivative is $2 x$, you are asking when |2 x| < 1 ...
4
Based on the assumption that those F functions produce scalar results…
If you just want to manipulate the vectors as entities without considering their components, then you can enter the function for F2s
f2s[q_, k1_] := (5/
14) + (3 (Norm[k1])^2)/(28 (Norm[q])^2) + (3 Norm[
k1]^2)/(28 (Norm[q - k1])^2) - (5)/(28 (Norm[q])^2 (Norm[
q - k1])^(-2)) - ...
1
This answer is also not direct answer because there is no Module or While but it is good to know that construct:
f[n_Integer /; n>0] := f[n] = f[n - 1]/(6 n) + n!
f[0] = 7
More here
3
Since you are interested in learning different ways to write this, here is one that avoids using "variables" entirely, thus removing the need for Module:
fnw[i_Integer] :=
Last @ NestWhile[{# + 1, 1/(6 #) #2 + #!} & @@ # &, {1, 7}, #[[1]] <= i &]
An expression such as #[[1]] <= i & is a pure function with a single parameter ...
3
You mean this?
fw[i_Integer] := Module[{n = 0, last = 7}, While[++n <= i,
last = 1/(6 n) last + n!;
];
last]
3
Jacob, allow me to suggest a presentation that I think you will find relevant and informative:
Working with Unevaluated Expressions - Robby Villegas
Some excerpts:
Unevaluated is a wrapper on arguments that is simply a signal to the
evaluator to avoid evaluating the argument. ... It is transparent to
the function receiving the argument. You can ...
0
I don't think you have found a bug. The evaluations you display seem in accordance with my understanding of how the Mathematica evaluation loop works.
I believe Mathematica looks first at the head of the argument given g to see if it matches the pattern _Symbol. If it doesn't, given your definition of g, Mathematica returns input expression unevaluated ...
5
I am currently developing an open source Genetic Algorithms library for Mathematica. It can be downloaded from this source.
It is documented and, although I have not used it for multi-objective applications, it should provide some help with such applications.
4
Actually this is more like a comment to Michael E.'s answer than an own answer, but it became too long for a comment. I think it is worth mentioning that $IterationLimit (and also $RecursionLimit and probably some others as well) is somewhat special and thus needs special treatment: For a "normal" variable it would be quite simple to achieve what Michael ...
5
Not sure about what you're trying to do, but this doesn't bring up errors:
ClearAll[f];
f[a_?NumericQ] := x /. FindRoot[x^2 - 1 == a, {x, a - 1, a + 1}]
NIntegrate[f[z], {z, 0, 5}]
(*
-> 9.13129
*)
Edit
The result is (of course) equivalent to
Integrate[Sqrt[1 + z], {z, 0, 5}]
(*
-> -(2/3) + 4 Sqrt[6]
*)
4
What this does is set a default value for iter, meant for use if cfRemainders is called with only one argument. The default value for iter in this case is $IterationLimit, and the Hold[] enclosing it means cfRemainders will use $IterationLimit symbol for the new rule. If there was no enclosing Hold[], $IterationLimit would have been replaced with the Integer ...
6
The original complete definition is
cfRemainders[x_, iter_: Hold[$IterationLimit]] :=
NestWhileList[FractionalPart[1/#] &, FractionalPart[x], # != 0 &, 1, ReleaseHold[iter]]
The iter_ : Hold[$IterationLimit] makes iter an Optional argument with the default value Hold[$IterationLimit] if the argument is omitted.
Secondly, by using Hold, ...
3
I would approach this by combining the functionality of bump given in:
Elegant manipulation of the variables list
with my step evaluation function described here:
How do I evaluate only one step of an expression?
The step function is needed to (easily) recover the expression {ttt[[1]], ttt[[2]]} from the definition of f without it fully evaluating. It can ...
1
Daniel is completely correct that this is a hard problem and will usually take a very very long time. However, the igraph library does have a function for it and you can call it through this package. Please read the instructions on how to set up the package, then do this:
{g, subG} = {PetersenGraph[5, 2], EdgeAdd[CycleGraph[5], 5 <-> 6]}
res = ...
3
You may use ReleaseHold[Hold[f = {3, 4}] /. OwnValues[f]] :
ttt = {1, 2};
f := {ttt[[1]], ttt[[2]]};
ReleaseHold[Hold[f = {3, 4}] /. OwnValues[f]]
?ttt
(* ttt -> {3,4} *)
Some explanations :
The fullform of f={3,4} is Set[f, List[3, 4]].
Set has attribute Holdfirst.
We want to transform Set[f, List[3, 4]] in {ttt[[1]], ttt[[2]]}={3,4}.
...
2
Your assertion is not correct (that Mathematica only runs the final line). Put your code in a text file (I called it "text.txt"). Then
<<"test.txt"
and it will run the code in the text file. It will not display the plots. You can do that from your notebook. For instance typing
a
shows the plot you have defined as a. You need to execute the Show ...
2
Well, I know of a simple solution: Combine both graphics into a list of graphics.
a=Plot[x^2 ,{x,0,2}];
b=ListPlot[{{0.327081,9.94393},{0.327081,0.102804}},Joined->True];
a1=Plot[26x^2 - 19x,{x,0,3}];
b1=Plot[-2x^2 ,{x,2,3}];
{Show[a,b,PlotRange->All,PlotLabel->hy],Show[a1,b1,PlotRange->All,PlotLabel->sx]}
Kind of simple, I know, but it ...
12
Implementation
The following implementation is based on expression serialization and SequenceAlignment built-in function. The idea is to break expressions into constituent parts, then align these part sequences, and then determine the positions where the expressions are different.
The auxiliary heads we will need are inert heads diff and myHold, the latter ...
2
For diff'ing code fragments/expressions, you can copy-and-paste as "Plain Text" into Quick Diff (online) or into WinMerge (PC-based), ref. http://stackoverflow.com/q/15655828/879601 (also mentions a Mac-based method using Bash).
E.g. WinMerge:-
(For diff'ing packages and notebooks I favour CSDiff.)
5
If you can convert expressions to text form, there's a possible answer here. I sometimes use it to compare notebooks:
notebook1 =
StringJoin[
Import["/tmp/freaky-illusion.nb", "Plaintext"]];
notebook2 =
StringJoin[
Import["/tmp/freaky-illusion-1.nb", "Plaintext"]];
System`Dump`showStringDiff[notebook1, notebook2]
3
One way is to put some of the code in a separate file, and then execute the code in the file using <<. This is the function Get which "reads in a file, evaluating each expression in it and returning the last one."
4
With a test.m file content of :
Print["Hello World"];
At the kernel:
In[1]:=<<"test.m"
Hello World
In[2]:=
Or, as an alternative run the file as a script
./MathKernel -script test.m
3
If you can hazard a guess as to the form of the function, then you can fit almost anything. For example, here is your data:
points = {{-2, 4}, {0, 0}, {1, 1}, {5, 25}}
Let's see how well a second order polynomial fits:
poly = NonlinearModelFit[points, a x^2 + b x + c, {a, b, c}, x]
The answer is: it fits really well! You can also pick other functional ...
3
Try Interpolation; the second form should do exactly what you want. This will return an InterpolatingFunction object, which you can apply to numerical arguments just like any other function.
if = Interpolation[{{-2, 4}, {0, 0}, {1, 1}, {5, 25}}]
I have if[3.2] returning 10.24.
2
Will some dynamic chart fit your needs?
I tried using dynamic things to track the change of variable values as followed.
First of all I need to filter out those context I'm not interested in. Unfortunately I don't know how to get built-in contexts, so I used a silly way, that is to run some random code before reading contexts:
Names["*`x"];
{Plot[x, {x, ...
10
General thoughts
I think that your mechanism is reasonably robust for common use cases, but not fully robust if one wants to take into account all possible ways that the value (or, generally, global properties) of the symbol can be changed in Mathematica.
My current opinion is that making such triggering mechanism fully robust without new system support is ...
Top 50 recent answers are included



