Skip to main content

Posts

Showing posts from September, 2015

Why a Precision problem for Floor of quotient of Logs?

This line returns a Precision problem: Floor[Log[9]/Log[3]] This one works fine: Floor[Log[9]/Log[3]//N] What I don't understand is why one works while the other doesn't because I assume that internally Mathematica would numerically evaluate the argument of Floor first anyway, so the two lines should be logically equivalent, the 2nd one just redundant. But clearly I was wrong. What did I misunderstand about how Floor works?

plotting - Creating a Mathieu stability diagram

I am attempting to re-create a Mathieu stability diagram like the one shown here: I expected that I could use MathieuC to generate this graph by assuming that instability occurs when the function returns a complex number, so I try Quiet@DiscretePlot[Re@a /. FindRoot[MathieuC[a, q, 1], {a, 0.2}], {q, 0, 1, 0.1}] which is wrong for two reasons - it produces a plot not even close to the desired output and the output is dependent on what value I use for z (in the example above, 1). For those interested, the impetus behind this problem is to explore how Mathematica can be used to simulate the behavior of a quadrupole mass spectrometer. Answer I think that this question is too localized as it concerns the physics of a specific scientific instrument. Nonetheless, it is upvoted, so here I provide an answer for the benefit of the voters. I would still be happy to discuss this in the chat. The mathematics of the quadrupole mass filter is more complicated than you might think. Basically, your

plotting - Opacity and overlapping multiple polygons

Let's say I have 100 polygons that are all different but most of them overlap. All I want to do is to draw/plot them in one single graphic with linearly adding gray values; i.e., a point with n overlapping polygons(or other graphics) should have a grayvalue of n/100 . I wish Graphics[{Opacity[1/10], Table[Disk[{i/10, 0}], {i, 10}]}] would work, but Opacity doesn't add up linearly, and I don't find any easy way to do what I want. My current idea is to go via Image[Graphics[...]] , ImageData and ArrayPlot , but I might lose a lot of precision that way. Answer I'm not very familiar with image-processing but I do not think you could get both, high precission and high performance, at once. This is straightforward approach. With Image processing functions avalible in Mathematica . Also, I'm not going to use Opacity , I do not know how does it work inside. First, there is a function to to create an image, you can set resulution like you need. f = ColorConvert[Image[

performance tuning - Delay Evaluation of First Argument of ConditionalExpression until Second Argument Evaluated

A particular set of equations I am solving, sol = Solve[...] yields a lengthy List of ConditionalExpression s, the arguments of which take a bit of time to evaluate (sol /. x -> .22) // AbsoluteTiming (* {0.26925, {...}} *) which adds up when performed for hundreds of values of x . This is so even though most instances of ConditionalExpression return Undefined , because both arguments of ConditionalExpression are evaluated, even when the second argument evaluates to False . A work-around is ((sol /. ConditionalExpression[z1_, z2_] :> ConditionalExpression[z1, z2 /. x -> .22]) /. x -> .22) // AbsoluteTiming (* {0.0504917, {...}} *) What alternatives are more compact or elegant? Answer The first solution is to use Unevaluated : sol := ConditionalExpression[Pause[y], y > 2] sol /. y -> 1 // RepeatedTiming {1.01, Undefined} So it takes the whole second to evaluate even though the condition is false. Now let's make a simple rule: rule = ConditionalExpression[

plotting - ParametricPlot3D: The Mesh shows some unexpected wires to the origin. How to remove them?

In the code below a hexagonal shape is defined and plotted. The ParametricPlot3D shows the hexagonal design almost as intended. However, the mesh makes some strange "wires" to x=y=0. This is unexpected as the function does not exist at these coordinates. Why am I seeing this strange behaviour at the center? How can the plot be improved? I tried several things: 2nd plot: I also included these coordinates in the Exclusions in the second plot but this didn't help. 3th plot: When the mesh is not plotted the graph looks better, altough some polishing at the edges might improve the graph further. 4th plot. Other problems is encoutered in the 3Dplot. Remove["Global`*"]; func[u0_, v0_] := Module[{u = u0, v = v0}, { u, v, If[u == 0 && v == 0, Null, θ = ArcTan[v, u]; θN = Mod[θ, 3.1415/3., -3.1415/6.](*θ w.r.t North*); l = Norm[{u, v}]; vN = l*Cos[θN ]; If[.3 < vN < .8, 2 - vN, Null] (*Make parabolic function(vN)*

arithmetic - How to do binary calculation?

For example, $a=0.10101$ in binary representation. Then how to calculate $a^2$ directly in mathematica? Is there any function turning binary into decimal? I only found its inverse... Answer You can input numbers in any base up to 36 using the notation base^^digits . Digits over 9 are represented using a , b , c , ... You can print numbers in any base up to 36 using BaseForm . Thus, In[1]:= a=2^^0.10101 Out[1]= 0.65625 In[2]:= BaseForm[a^2,2] Out[2]//BaseForm= Subscript[0.0110111001, 2] Note that the internal representation of numbers doesn't know or care about bases. These tools are only for inputting or printing numbers, but do not affect how numbers are stored internally. The internal representation is always binary. IntegerDigits / RealDigits and FromDigits will convert numbers to/from an explicit list of digits . These functions work with any base, not just up to 36.

plotting - Get Y-Axis of FFT in decibels

I am trying to make a plot of a sound file similar to Audacity's FFT plot which looks like this when the x-axis is on a log scale: My plot of the same sound file (below) has the problem that the units are in absolute amplitude, not decibels. How can I fix this? Answer decibel is a relative unit. I'm pretty sure there is no implied standard reference in audio processing, (it looks like audiologists have a few go-to's e.g. dB HL, but I don't know what Audacity does). That said, you need a reference value. Since you're looking at FFT's the total power might be a good choice. Then decibels will tell you how strong a particular frequency is relative to the signal. signal = RandomReal[{0,1},1000];(*A random signal*) fft = signal//Fourier//Abs; fft = fft[[1;;Ceiling[Length@signal/2]]]; (*Since we're looking at power only take the first N/2 points.*) fftPowerRef = Total[fft^2]; (* Power is amplitude squared. *) inDecibels = 10*Log[10, fft^2/fftPowerRef ]; In

system variables - How to set the timeout value for *Data functions

I haven't measured this precisely but it seems the default timeout value for retrieving EntityValue s with *Data functions is in the range of tens of seconds. This significantly impacts the execution time if the *Data function is called repeatedly, because I often get an EntityValue::timeout: A network operation for EntityValue timed out. Please try again later. >> error. Is it possible to manually set the timeout value for such functions that retrieve curated data from Wolfram servers? Answer You could wrap the call to the *Data function in TimeConstrained . This function will evaluate its argument for the maximum number of seconds specified. If the computation has not completed in that time, it will return $Aborted . Of course, you will probably have to manage the aborted computation somehow, but from my reading of your question that doesn't seem to be a problem. For instance: TimeConstrained[WeatherData["Chicago", "Temperature", {1950, 1}], 0.1

numerics - Higher order periodic interpolation (curve fitting)

I have a list of points in 3D, and I want to get a smooth interpolation or curve fit (it is more for illustration) of these points such that the first and second derivatives at the start and end points agree. With ListInterpolation[pts1, {0, 1}, InterpolationOrder -> 4, PeriodicInterpolation -> True] even the first derivatives do not agree. Answer It does seem that the options PeriodicInterpolation -> True and Method -> "Spline" are incompatible, so I'll give a method for implementing a genuine cubic periodic spline for curves. First, let's talk about parametrizing the curve. Eugene Lee, in this paper , introduced what is known as centripetal parametrization that can be used when one wants to interpolate across an arbitrary curve in $\mathbb R^n$. Here's a Mathematica implementation of his method: parametrizeCurve[pts_List, a : (_?NumericQ) : 1/2] /; MatrixQ[pts, NumericQ] := FoldList[Plus, 0, Normalize[(Norm /@ Differences[pts])^a, T

summation - Problem with extracting a constant multiplier out of sum

For a generic symbol A[i] 2 Sum[A[i], {i, 1, n}] == Sum[2 A[i], {i, 1, n}] does not return True . Is there any reason behind these behaviors? Do we have any way to evaluate the equation correctly? ADDED: I would like to thank everyone who noted the comments. I am afraid my use of Simplify makes everyone confused. I want to ask not the behavior of Simplify , but that of Sum and Equal . Is it intentional or kind of a "bug"? Edited: What I would like to ask is about Sum and I have not intended to ask the use of Simplify . So, I edited the title again. As I have written below, mathematically Sum[2 ..] is equivalent to 2 Sum[..] . I thought that as long as mathematically correct, Mathematica returns immediate values, especially for trivial cases, just like the examples of a + b == b + a or a b == b a . Does not this hold for Sum ? Do we have any way to let Mathematica evaluate the relation mathematically correctly? This is my question. I am sorry if my question was ambiguous.

plotting - Extracting the contour lines from an image

The Image presented is created by Mathematica ListPLot . It's a list of points out of a 512x512 grid, which meets criteria. I would like to be able to identify the points that make the contour, inside and outside, of the green "ears". Then with these points identified, average over the two contours and have a line that draws the shape. I'm not sure if this can be done in Mathematica and if it can, how to implement it. Any help would be appreciated Update Another option would be to use a more restrictive criterion, which gives a plot like this. Is there a way to make Mathematica connect the points and/or make a list of these points? Answer If you can specify your criteria as an set of inequalities: criteria = x^4 + y^4 <= 1 && x^2 + y^2 > 0.5^2; you can simply use ImplicitRegion and RegionBoundary : r = ImplicitRegion[criteria, {x, y}] Region[RegionBoundary[r]]

notebooks - Capturing an F1

I teach an Intro to Mathematica course, and one of the things I try to reinforce early on is just how helpful Mathematica's help is. In the very first lab for the course, I even give the students a randomly selected command (from among simple ones like PrimeQ , IntegerDigits , etc.) and ask them to tell me what that command does. As of right now, they get this question right if they correctly explain what the given command does. What I'd like to do is make sure they are actually going to the help. Is there some way to capture an F1 key press within an EventHandler or something similar? Answer You could add a trap to Documentation`HelpLookup which is called when F1 is pressed: Unprotect[Documentation`HelpLookup]; Documentation`HelpLookup[link_String, nb_, lang_String, opts : OptionsPattern[]] := Block[{$inblock = True}, lookedup[link] = True; Documentation`HelpLookup[link, nb, opts]] /; ! TrueQ[$inblock] You can add whatever code you want. As an example I assign a d

Why does args symbol exist in a fresh kernel?

In fresh kernel Mathematica 11.3 (Linux) asking for args (similarly for dims) I obtain ??args Global`args As far as I remember similar problem we had in 10.x with the symbol z See Seems like Global context is again polluted with args and dims as is confirmed by Names["Global`*"] Answer It's a type of otherwise harmless bug that tends to come and go with versions. I would suggest to report it to Wolfram, but also not to worry about it. Notice that the symbols have no associated definitions, which means that they will not interfere with your code. A potential way in which such a situation can arise is the following. Imagine you put Sqr[x_] := x^2 in your $UserBaseDirectory/Kernel/init.m file. It will cause not only Sqr to be created in the Global` context, but also x , which is easy to overlook. This is completely harmless though, and will not interfere with any x symbol you might use in your session. A case that is a bit more realistic, and better shows why the

list manipulation - How to delete unnecessary resistances in a resistance network

I'm still dealing with resistance network processing and got one problem left: how to delete unnecessary resistances? Background Let's assume we are junior high students and know nothing about Kirchhoff's laws. We only know about how to calculate parallel resistances equivalent serial resistances and how to convert between star- and triangle topologies However, the first step of the calculation process is to determine which resistances are relevant and which are not (when looking at the equivalent resistance between some points in the network). At this I got stuck. Main Problem From now on I'll use edges in graphs to represent resistances Some resistance's existence contribute nothing to the entire network: For example, when calculating resistance between point 1 and point 4 in this network: Graph[{1 <-> 2, 2 <-> 3, 3 <-> 4, 5 <-> 2, 6 <-> 3}, VertexLabels -> "Name", VertexCoordinates -> {{0, 0}, {1, 1}, {2, 1}, {3, 0},

plotting - How can I save both the plot and the legend together?

In this example, how can I put the legend inside the graph? Currently, when I save the graph, only the graph is saved, not the legend. Expr1 = -2 p + 1 Expr2 = 2 p - 1 Expr3 = p - 1/2 Plot[{Expr1, Expr2, Expr3}, {p, 0, 1}, BaseStyle -> AbsoluteThickness[4], PlotLegends -> LineLegend["Expressions", BaseStyle -> AbsoluteThickness[4]]] Solve[Expr1 == Expr2, p] Also, how can I insert the solution in the last line, also inside the graph? Here you can see the result: Answer This is how to save the graph, legend and all: Another way would be to use Rasterize : Rasterize[Plot[...]] The legend and the graph is now one image.

output formatting - TeXForm and large brackets (Biggl[ etc)

Goal I am trying to export a very long expression like expr = c1*bracket1[a+b+c2*bracket2[d+e+f...]]+... to LaTeX using TeXForm . bracket1[arg_] should end up as \Biggl\{ \Biggr\} , bracket2[arg_] as \biggl \biggr] and so on. What I have What I have managed so far is defining a format for bracket1 and bracket2 that adds text before and after the argument: Format[bracket1[arg_]] := Row[{"beginbracket1",arg,"endbracket1"}] Format[bracket2[arg_]] := Row[{"beginbracket2",arg,"endbracket2"}] This renders expr (without the ellipsis) as In[1] := expr//TeXForm Out[1] := \text{c1} \text{beginbracket1}a+b+\text{c2} \text{beginbracket2}d+e+f\text{endbracket2}\text{endbracket1} What I have not / Questions The above does not work if I include TeXForm in the Format definition. I think I read somewhere that the TeXForm is not distributed to the recursive calls of Format during formatting. The implementation above leads to StandardForm being cluttere

front end - Changing default window appearance

Since every single time I start Mathematica, my first action is aligning the windows properly (Notebook on the left for $2/3$ of the screen, help on the right for the other $1/3$), I was wondering whether this could be done automatically. This is what it looks like: How could I make Mathematica to use these window positions and sizes by default? Answer The help window position can be set to be remembered from the Options Inspector: open it, select Global preferences, go to Global Options -> Dialog Settings -> Help Viewer Settings and set Enabled to True .

functions - Is the renaming mechanism of `With` flawed?

I'm confused about the renaming mechanism of With : With[{x = a}, Hold[With[{a = b}, a + 2 x]]] (*==>Hold[With[{a$ = b}, a$ + 2 a]]*) With[{x = a$}, Hold[With[{a = b}, a + 2 x]]] (*==>Hold[With[{a$ = b}, a$ + 2 a$]]*) The documentation tells us that With constructs can be nested in any way, with inner variables being renamed if necessary. There is name conflict in the first case, so renaming is quite reasonable. However, in the second case, there is no name conflict at all, why Mathematica renames a to a$ ? I've checked some simple cases which all show that With does the renaming work simply by appending $ to var (with the exception that var ending with only one $ is untouched): With[{x = a}, Hold[With[{aa$ = b}, aa$ + 2 x]]] (*==>Hold[With[{aa$ = b}, aa$ + 2 a]]*) With[{x = a}, Hold[With[{aa$$ = b}, aa$$ + 2 x]]] (*==>Hold[With[{aa$$$ = b}, aa$$$ + 2 a]]*) If this is really the underlying renaming mechanism, IMHO, this will be dangerous. As can be seen from

evaluation - Generate list of strings from a list of assigned variables

How do I generate a list of strings from a list of assigned variables? E.g. convert var1 = 10; var2 = 11; var3 = 17; var4 = 5; compvar = {var1, var2, var3, var4}; (*all variables assigned*) into compvarstr = {"var1", "var2", "var3", "var4"}; Using ToString obviously converts the variables assignments into strings e.g. compvarstr = ToString[#] & /@ compvar gives, {"10", "11", "17", "5"} I'm after the unassigned variable names as strings e.g. {"var1", "var2", "var3", "var4"}; Apologies if this is a duplicate - I had a bit of a look and nothing seemed to answer it. Answer You must introduce some form of holding in you definition of compvar as otherwise, assuming it is defined after var1 , var2 , etc., there is no information to retrieve: var1 = 10; var2 = 11; var3 = 17; var4 = 5; compvar = {var1, var2, var3, var4}; Definition[compvar] compvar = {10, 11, 17,

dynamic - Graphics can't be live and editable

Is there a way to construct an interface so that the Code and the Graphics remain in sync? For example I would like to be able to drag/drop and move around different shapes in Graphic while seeing the code change. Then I would like to edit the code so the graphic changes. Updated image to clarify interface I'm aware that you can see the graphics source by hitting Ctrl + Shift + E , but this isn't ideal because the graphics source code is often in the displayform and much more verbose. Additionally it doesn't allow me to see how the code changes while I am editing the code. I'm working on some code that uses dynamic currently, but I'm not sure of the right technique just yet. EDIT: Both the InputField and the Graphics should be live and editable. The problem currently is that the the Graphics elements can't seem to be Dynamic. If you set it as Dynamic it is impossible to re size and move the elements around. Answer I am still working on the code, but I have

front end - Syntax highlighter shows error for Manipulate when it's inside a Block or a Module

I'm putting my new copy of Mathematica 10 through its paces and I noticed a weird change in the colouring scheme that I find very annoying, and I'd like to get some insight into why it's happening. The change happens, as far as I can tell, for variables that have been set in some scoping construct which are then used inside of a Manipulate command. Thus, for example, the code Module[ {A = 1}, Manipulate[ Plot[ A Sin[k x] , {x, 0, 20} ] , {k, 1, 10} ] ] renders differently in the Mathematica 9 and 10 frontends: Playing around in Edit > Preferences > Appearance > Syntax Coloring > Errors and Warnings, the error class that this is attributed to is Variables that will go out of scope before being used though what that means exactly isn't very clear to me. Therefore, I have some questions: Is this in fact an incorrect usage? If so, why, and what alternative construct should I use? (I notice, in particular, that in version 10 the red colour is di

differential equations - Solver for unsteady flow with the use of the Navier-Stokes and Mathematica FEM

There are many commercial and open code for solving the problems of unsteady flows. We are interested in the possibility of solving these problems using Mathematica FEM. Previously proposed solvers for stationary incompressible isothermal flows: Solving 2D Incompressible Flows using Finite Elements http://community.wolfram.com/groups/-/m/t/610335 FEM Solver for Navier-Stokes equations in 2D http://community.wolfram.com/groups/-/m/t/611304 Nonlinear FEM Solver for Navier-Stokes equations in 2D Nonlinear FEM Solver for Navier-Stokes equations in 2D We give several examples of the successful application of the finite element method for solving unsteady problem including nonisothermal and compressible flows. We will begin with two standard tests that were proposed to solve this class of problems by M. Schäfer and S. Turek, Benchmark computations of laminar flow around a cylinder (With support by F. Durst, E. Krause and R. Rannacher). In E. Hirschel, editor, Flow Simulation with High-Perform

import - How can I read compressed .Z file automatically by Mathematica?

When I read .Z file by something like jpldatstring = Import["ftp://cddis.gsfc.nasa.gov/products/jpl/2003/jplg0040.04i.Z"] Unfortunately, it turned out that "Import::infer: "Cannot infer format of file !(\"jplg0040.04i.Z\")"". Indeed, the form “.Z” isn’t included in the ImportFormats. Mathematica can read other types of compressed file included in $ImportFormats quite well such as “GZIP”,”ZIP”, “TAR”. The .Z files I deal with can be uncompressed by certain software. But there are thousands of them added up to several GBytes , so an automatic way is needed. How can it be done in Mathematica? The compressed .Z files can be uncompressed by 'uncompress' order under Linux, so is there any way to code Linux order into Mathematica program? The dat example can be downloaded from ftp://cddis.gsfc.nasa.gov/products/jpl/2003/ The commit of george2079 shows a way out: dat = Import[ "!uncompress -c /mnt/data/home/huangjp/magnphy/jpl/jplg0040.04i.Z