Skip to main content

Posts

Showing posts from March, 2014

list manipulation - Finding all length-n words on an alphabet that have a specified number of each letter

For example, I might want to generate all length n=6 words on the alphabet {A, B, C} that have one A , three B 's and two C 's. An example of such a word is: 'ABBBCC' . I'd like to generate all such words. I've already tried generating all permutations of a particular string (like 'ABBBCC' ) and deleting all duplicates. This is too slow for my purposes. Answer Permutations is already duplicate-aware: Permutations[{"A", "A", "B"}] {{"A", "A", "B"}, {"A", "B", "A"}, {"B", "A", "A"}} Perhaps you are looking for combinations of a particular length (which can then be permuted). One way to get those is this: f[k_, {}, c__] := If[+c == k, {{c}}, {}] f[k_, {x_, r___}, c___] := Join @@ (f[k, {r}, c, #] & /@ 0~Range~Min[x, k - +c]) Use: f[4, {1, 3, 2}] {{0, 2, 2}, {0, 3, 1}, {1, 1, 2}, {1, 2, 1}, {1, 3, 0}} These represent the words of l...

Mathematica: Retrieving PlotRange from Histogram

I know that one can retrieve PlotRange of a plot by using AbsoluteOptions[plot,PlotRange] but that won't work on Histogram . Here an example: In[1099]:= data = {-1.2056, -1.46192, -1.30053, -2.52879, -0.99636, -1.73904, -1.164, -1.83398,-0.97505, -0.503256, -0.63802, -0.785963, -0.711821, -0.820439, -1.8699, -3.9659, -1.4456, -1.67021, -1.42009, -2.5644, -1.45002, -1.27806, -1.66529, -1.67073, -3.31102, -3.38638}; Histogram[%, PlotRange -> Automatic]; AbsoluteOptions[%, PlotRange] When running the code I get the following message. PlotRange::prng: Value of option PlotRange -> {{All,All},{-4.,0.}} is not All, Full, Automatic, a positive machine number, or an appropriate list of range specifications. >> As I understood the documentation, PlotRange need to be of a certain format (e.g. two numbers) and {{All,All},{-4.,0.}} apparently does not fit to that format, for which reason Mathematica won't give me back the PlotRange of my histogram. Does anybody know how I ca...

Using the Nest function -- Confusion on my output

I have the following code and output where the original function is $f(x,a) = a^2 - x^2$. f[x_, a_] = a - x^2 ref := Nest[Function[{u, v}, f[u, v]][x, y], x, 2] ref (-x^2 + y)[(-x^2 + y)[x]] I want the second iteration of this function. i.e, $f(f(x)) = a^2 - (a^2 - x^2)^2$. Why am I not getting this? Answer In your code, you give a 2-argument function as the first argument to Nest , but then only one expression. From the documentation, I only see examples of Nest being given a single argument. Here I use a single-argument function, since that seems to match the output you want, f[x_, a_] = a^2 - x^2; Nest[Function[x, f[x, a]], x, 2] (* a^2 - (a^2 - x^2)^2 *)

plotting - How do I feed data points into an equation to solve NUMERICALLY?

I start with this equation and solve it numerically for $z(x,y)$ in the range $1 $$ \frac{3}{xyz} - 2x - 3y - 5z = 0 $$ Then using the data points of $z$ above, I want to solve for this special condition: $$ x + y + z = 0 $$ Then I want to plot a graph of $y(x)$. Everything must be done numerically. eqn1 = 3/(x y z) - 2 x - 3 y - 5 z == 3 ContourPlot3D[Evaluate[eqn1], {x, 1, 5}, {y, 1, 5}, {z, 0, -5}] fulldomain = Table[z /. Solve[eqn1, z, Method -> Reduce], {x, 1, 5, 1}, {y, 1, 5, 1}] ; eqn2 = x + y + z == 0 special = Table[y /. Solve[eqn2 /. fulldomain, y, Method -> Reduce], {x, 1, 5, 1}] ifun = Interpolation[special] Plot[ifun[x], {x, 1, 5}, Epilog -> Map[Point, special]] Answer There is a difficulty with the statement of the problem. Generally the problem can be solved as shown below. In this case there is a stipulation that $1 If we agree to use only numerical techniques and pretend that Solve (nor NSolve ) will not produce solutions, then FindRoot is th...

list manipulation - Computing the equivalence classes of the symmetric transitive closure of a relation

I have a list of pairs, for example: pairs={{13, 10}, {12, 14}, {10, 36}, {35, 11}, {3, 5}, {1, 6}, {20, 24}, {21, 22}, {33, 7}, {31, 8}, {31, 27}, {32, 25}, {21, 35}, {34, 19}, {18, 15}, {14, 16}, {9, 5}, {4, 7}, {1, 13}, {15, 2}, {6, 36}, {4, 34}, {8, 2}, {9, 3}, {25, 20}, {19, 26}, {22, 11}, {23, 12}, {32, 28}, {30, 33}, {23, 16}, {24, 17}, {29, 27}, {26, 30}, {17, 28}, {18, 29}}; pairs can be seen as the definition of a relation $R$. $x$ and $y$ satisfy the relation if and only if {x,y} $\in$ pairs . I need to compute the equivalence classes of the symmetric transitive closure of $R$. In other words, I need to compute a list eqvclss . The elements of eqvclss are lists themselves. For example, 13, 10, 36, 6, 1, ... should all be in the same list in eqvclss . (If you understand that, then I explained the question properly; if you don't, say so in the comments so I can try to improve). Answer ConnectedComponents Using Daniel Lichtblau's answer to a related question Conne...

kernel - Save open Mathematica Notebook from command line or second Notebook to avoid data loss

I was executing a long Mathematica Notebook over night. The Mathematica instance is running on a Linux workstation (in a vnc server session to be precise). Now I cannot access this session anymore, which means that I likely loose the output data which was produced during the run. I can still login on the workstation as the same user and run Mathematica there. I know from the process list that Mathematica is still running, but I cannot access the GUI anymore. So, if there would be a remote control for Mathematica from command line or a second worksheet, which allows me to save the worksheet, I could prevent the data loss. I already tried to run a second instance of Mathematica but it seems that I cannot even see the Kernels there. Any ideas? It would save my day.

Impossible to bypass evaluation on returned values?

Following all the great advice on this other question , I'm now fluent with HoldAllComplete and Unevaluated on the input side of quote-type functions. I continued my investigations and produced the following attempt at a generic conversion from expression to captive (or quoted) expression: ClearAll[captive]; SetAttributes[captive, HoldAllComplete]; captive[expr_ /; AtomQ @ Unevaluated @ expr] := expr captive[head_[args___]] := {captive @ head} ~Join~ (captive /@ (Unevaluated @ {args})) captive[x___] := Throw[{x}]; This is really great and handles almost all my scenarios. To wit, the following abbreviated test set produces the desired results testSet = {"foo", foo, 12, 0, 3/4, 3.14, 2.72 + 3.14 I, Infinity, {1, 2, 3}, {1, "a", b}, f, f[b], f[1, "a", b], f[{}], f[{1, "a", b}], f[a][b], f[a][1, "a", b], f[a][{}], f[a][{1, "a", b}], Hold[Plus @@ {}], Hold[Plus @@ {1, 2, 3}], Plus @@ {1, "a", b}, 1 + ...

programming - HoldFirst and inserting additional options into a Grid of Graphics

This is related to my earlier question , but is specific to an issue I have encountered with the use of the HoldFirst First, let's create some fake data for testing purposes. dateARList = With[{ar = FoldList[0.9 #1 + #2 &, 0., RandomReal[NormalDistribution[0, 1], 100]]}, Transpose[{ Table[DatePlus[{2000, 1, 1}, {n, "Month"}], {n, 0, 100}], ar}] ]; Now define two functions. First, the general one that doesn't assume the size of the matrix in the first argument. Clear[testHolder, testHolder2] Attributes[testHolder] = {HoldFirst} testHolder[m_?MatrixQ, rest : OptionsPattern[{Graphics, Grid}]] := Module[{nc, nr, subrules, subargs}, {nr, nc} = Dimensions[m]; subrules = Table[Cases[HoldForm[m[[i, j]]], _Rule], {i, nr}, {j, nc}]; subargs = Table[Cases[HoldForm[m[[i, j]]], Except[_Rule]], {i, nr}, {j, nc}]; Grid[Table[ Head[m[[i, j]]] @@ Join[subargs[[i, j]], subrules[[i, j]], {PlotLabel -> {i, j}, Joined -> True} ], {i, nr}, {j, nc}], ...

regular expressions - Regex named groups -- how to refer back to them in the replacement string

We can use group numbers to reuse the same piece of code while inside regex string, like that: StringCases["x = y", RegularExpression["([\\w\\s]+)=(?1)"]] {"x = y"} To make it more readable and robust (like avoiding the situation when the groups can be renumbered either internally or through a redesign of the regex code), we can name patterns (and yes, (? ) / (?&n) syntax works as well as (?P ) / (?P>n) ): StringCases["x = y", RegularExpression["(? [\\w\\s]+)=(?&var)"]] StringCases["x = y", RegularExpression["(?P [\\w\\s]+)=(?P>var)"]] {"x = y"} {"x = y"} Perfect so far. However, what if I want to use the groups in the replacement rule? This works: StringCases["x = y", RegularExpression["([\\w\\s]+)=((?1))"] :> {"$1", "$2"}] {{"x ", " y"}} But this doesn't: StringCases["x = y", RegularExpression["(? [...

graphics3d - plotting 3d points: z-axis is squashed

I am plotting 3D points and it occurs to me that Mathematica doesn't have an easy way to specify my points to be plotted in a uniformly scaled cartesian space. For example I plotted Show[ListPointPlot3D[{{0, 0, 0}, {1, 2, 3}}], AspectRatio -> Automatic, PlotRange -> Automatic] And I get this: I would like to be looking at a box with the dimensions 1,2,3, not something like 3,3,1. The AspectRatio and PlotRange do not help, by the way.

performance tuning - Faster way to extract partial data from AdjacencyMatrix

I am dealing with a lot of Graph objects. One task is to obtain an Id for each of them. So I first used g = Graph[{1 -> 2, 1 -> 3, 4 -> 2, 3 -> 5, 4 -> 5, 7 -> 2, 4 -> 7, 3 -> 8}]; GraphId[g_] := Module[{}, AdjacencyMatrix@CanonicalGraph@g] FullForm@GraphId@g which gives SparseArray[ Automatic, List[7,7], 0, List[ 1, List[ List[0,2,5,5,6,8,8,8], List[List[5],List[7],List[4],List[6],List[7],List[7],List[3],List[6]] ], List[1,1,1,1,1,1,1,1] ] ] I have to reduce this result to save space. The first approach is not to including List[1,1,1,1,1,1,1,1] in the result. So I tried ToData[g_] := (Last@ToExpression@StringReplace[ToString@FullForm@g, "Graph" -> "List"])[[1]] GraphIdReduced[g_] := Module[{}, ToData@CanonicalGraph@g] FullForm@GraphIdReduced@g which gives SparseArray[ Automatic, List[7,7], 0, List[ 1, List[ List[0,2,5,5,6,8,8,8], List[List[5],List[7],List[4],List[6],List...

Plotting contours of a function for different values of a parameter

I want to draw a picture of $(x-t)^2 + (y-t^2)^2 - t^2$ in $xy$ plane, with different values of $t$. I did it in a very silly way , namely, ContourPlot[{ (x - 1)^2 + (y - 1)^2 == 1, (x - 2)^2 + (y - 4)^2 == 4, (x - 3)^2 + (y - 9)^2 == 9, (x - 4)^2 + (y - 16)^2 == 16, (x - 5)^2 + (y - 25)^2 == 25, (x - 6)^2 + (y - 36)^2 == 36, (x - 7)^2 + (y - 49)^2 == 49, (x - 8)^2 + (y - 64)^2 == 64, (x - 9)^2 + (y - 81)^2 == 81, (x - 10)^2 + (y - 100)^2 == 100, (x + 1)^2 + (y - 1)^2 == 1, (x + 2)^2 + (y - 4)^2 == 4, (x + 3)^2 + (y - 9)^2 == 9, (x + 4)^2 + (y - 16)^2 == 16, (x + 5)^2 + (y - 25)^2 == 25, (x + 6)^2 + (y - 36)^2 == 36, (x + 7)^2 + (y - 49)^2 == 49, (x + 8)^2 + (y - 64)^2 == 64, (x + 9)^2 + (y - 81)^2 == 81, (x + 10)^2 + (y - 100)^2 == 100 }, {x, -110, 110}, {y, -110, 110} ] I am sure there must be a simpler way. Could you give me a hand? Answer Use Table to generate the values for different t : ContourPlot[Evaluate@Table[(x - t)^2 + (y - t^2)^2 == t^2, {t, -...

equation solving - How to eliminate variables when using Solve[]

In certain problems, we need to solve systems of equations and get results in terms of just selected variables. For example, how could we solve eqn==0 below for c3 and c4 expressed in terms of c1 and c2 only, without a1 or a2 ? eqn = {{c1, c2}, {c1, c3}, {c1, c4}, {c2, c3}}.{a1, a2} - {5, 2, -4, -3} We can select two equations from the system and solve them for a1 and a2 , then substitute those results back in... asoln = Solve[eqn[[{1, 2}]] == 0, {a1, a2}]; b = eqn /. asoln; Solve[b == 0, {c3, c4}] (* {{c3 -> 1/5 (3 c1 + 2 c2), c4 -> 1/5 (9 c1 - 4 c2)}} *) This approach works but it requires that we find a subset of equations from which a1 and a2 can be solved for unambiguously, which might be difficult. Is it possible to make Solve[] eliminate a1 and a2 for us? Answer It turns out Solve[] has a feature that doesn't appear in the online documentation that I could find. A third argument can be added, a list of variables to be eliminated from the solution: Solve...

dynamic - Control variable and body variable decoupling in Manipulate

This issue was raised as an offside problem in this thread . Consider the following example, that does not work as expected: Manipulate[{x, r}, {{x, r}}, {r, 0, 1}] Note that as r is manipulated the InputField of x is updated (as the initial value of x is set to be r ) but not the x displayed as the body of the Manipulate . Interestingly, if x depends on r in a different way (endpoints of range instead of initial value) the example works as expected: whenever r is changed it changes both the displayed values of x : Manipulate[{x, r}, {x, r, 1}, {r, 0, 1}] It seems like that in Manipulate changing a variable ( r ) does not trigger a re-evaluation of the initial-value-dependent variable ( x ) displayed in the body though its value displayed in the control is updated correctly. I have no idea why the first example does not work the same way as the second does. While it might be said that this is a feature, I would argue that the unexplained decoupling of the two representations...

plotting - ListContourPlot and ListContourPlot3D use better interpolation for arrays of values than for lists of tuples (i.e. {{x,y,z,f[x,y,z]}..}

From reading the documentation, it seems that ListContourPlot3D should work equally well on an array versus a list of tuples, ?ListContourPlot3D ListContourPlot3D[array] generates a contour plot from a three-dimensional array of values. ListContourPlot3D[{{$x_1$,$y_1$,$z_1$,$f_1$},{$x_2$,$y_2$,$z_2$,$f_2$},$\ldots$}] generates a contour plot from values defined at specified points in three-dimensional space. But below the plot on the left uses the tuples version while the plot on the right uses the array, dta = Table[{x, y, z, x^3 + y^2 - z^2}, {z, -2, 2, .1}, {y, -2, 2, .1}, {x, -2, 2, .1}]; Grid[{{ListContourPlot3D[Flatten[dta, 2], Contours -> {0}, Mesh -> None], ListContourPlot3D[dta[[All, All, All, -1]], Contours -> {0}, Mesh -> None, DataRange -> {#, #, #} &@{-2, 2}]}}] The interpolation used for the array version is clearly superior. Why is this? InterpolationOrder is not an option for ListContourPlot3D (even an undocumented one). Applying the ...

graphics - DynamicLocation usage

Background DynamicLocation can be very useful: LocatorPane[Dynamic@x, Graphics[ { EdgeForm @ Thick, FaceForm @ None, Rectangle[BoxID -> "box"] , Arrow[{Dynamic[x], DynamicLocation["box", Automatic]}] } , PlotRange -> 2 ] ] but I don't know much about it. It was introduced to me by Szabolcs somewhere around this topic: Find inset bounding box in plot coordinates . It is extensively used in Graph related plots, e.g. to make edge arrows pointing neatly to the edge of a vertex shape. As shown above it can be used to specify position in Graphics with respect to primitives' boxes. So we can point e.g. Arrow to a Recangle, without knowing it's position, which was previously marked by BoxID . ( see more: BoxID in InputField focus ) It also accepts more arguments which can e.g. automatically point to the closest point on marked primitive. Something that would normally cost us calling the kernel for some region related procedures. Ques...

plotting - Table and ListPlot3D

I would like to do a ListPlot3D of an empirical function where variables c and d are my x and y axes and tkappa is my z. I either get an empty plot or axis ranges that do not correspond to values of c, d or tkappa. If I use the code below; I get an empty plot but the axis ranges are correct. tkappa[a_,b_,c_,d_]:= 0.67 - 0.07*a - 0.17*b + 0.40*c + 0.32*d + 0.16*a*b + 0.13*a*c-8.093*10^-4*a*d + 0.13*b*c + 0.084*b*d + 0.27*c*d - 0.10*a*b*c + 0.016*a*b*d+0.051*a*c*d + 0.16*b*c*d -0.059*a*b*c*d; timingData = Table[{c,d,tkappa[0,0,c,d]},{c,0,1,0.1},{d,0,1,0.1}] ListPlot3D[timingData] If I use a Table function as an argument for ListPlot3D, I get a surface but the axis ranges don't seem to correspond to c, d or values for tkappa. ListPlot3D[Table[tkappa[0,0,c,d],{c,0,1,0.1},{d,0,1,0.1}]] What is the best approach for ListPlot3D for x,y,z plots? Answer The data feed to ListPlot3D should be of the form {{x1,y1,z1},{x2,y2,z2},....} timingData = Partition[ Flatten[Table[{c, ...

Make the code shorter for solving Fizz buzz

Here is Fizz buzz Write a program that prints the integers from 1 to 100. But for multiples of 3 print "Fizz" instead of the number and for the multiples of 5 print "Buzz". For numbers which are multiples of both 3 and 5 print "FizzBuzz". I found the python version is much shorter, so I decided to write a short one, I have wrote several version Table[If[# != {}, Row@#, n] &@({Fizz}[[Sign[n~Mod~3] + 1 ;;]]~Join~{Buzz}[[Sign[n~Mod~5] + 1 ;;]]), {n, 100}] StringJoin@{If[#~Mod~3 == 0, "Fizz", ""], If[#~Mod~5 == 0, "Buzz", ""]} /. "" -> # & /@ Range@100 d = Divisible; Range@100 /. {_?(#~d~15 &) -> FizzBuzz, _?(#~d~3 &) -> Fizz, _?(#~d~5 &) -> Buzz} Can you show a more shorter one? Answer 67 63 56 55 (47?) characters Better: Row@Pick[{Fizz,Buzz},#~Mod~{3,5},0]/._@{}->#&~Array~100 In the rule-bending spirit of Code Golf, 47 characters : Pick[Fizz^Buzz,#~Mod~{3,5},0]/. 1-...

plotting - How to make frame ticks' labels have same number of digits after decimal point?

I'm making the ticks labels of my plot using the rule: FrameTicks -> {{N@FindDivisions[{Min@data1, Max@data2}, 6], None}, {Range[1960, 2015, 10], None}} This is generating the ticks I want on both axes pretty well. The only problem is that the y-axis ticks vary in the number of decimal places, which I do not want. Is there a way to make all those numbers have the same number of decimal places as the one with the most decimal places? I wanted to use something like NumberForm[ticks, {∞, n}] with ticks being the N@..., 6] above, but I'm not sure what n should be to just go with the tick mark with the most decimal places. Thank you! Answer First, generate the ticks and their labels with whatever range is desired. ticks[min_, max_] := Module[{d = FindDivisions[{min, max}, 6], n}, n = Ceiling@Log10@Max@Denominator@d; {#, NumberForm[#, {∞, n}]} & /@ N@d] For instance, t = ticks[.01,.03] (* {{0.01, NumberForm[0.01, {∞, 3}]}, {0.015, NumberForm[0.015, {∞, 3}]}, ...

syntax - Extra empty lists as function arguments

Consider the following piece of code: Options[f] = {Option -> True}; f[x_, OptionsPattern[]] := Module[{option}, option = OptionValue@Option; If[option, x + 1, x] ] f[4, {{}, {}}, Option -> True, {}, {}] f[4, {{}}, {}, {}] f[4] 5 5 5 Why does the function f ignore that empty lists and returns the same output as without them instead of returning the same input ? How this behaviour can be avoided ? Answer Why does the function f ignore that empty lists ... This is because options can be given in a list, so they can easily be stored and passed around. opts = {PlotRange -> {-2, 2}, PlotStyle -> Red}; Plot[Sin[x] + Sin[1.4 x], {x, 0, 10}, Evaluate[opts]] From OptionsPattern : OptionsPattern matches any sequence or nested list of rules, specified with -> or :> . Thus an empty list will match, and it is equivalent to giving no options. How this behaviour can be avoided ? The best answer really depends on why you want to avoid this, so I am going to stop here. ...

differential equations - Problem with WhenEvent in solving a PDE with NDSolveValue

I have problem with my PDE. The problem is as bellow: I used "WhenEvent" operator to solve it. The code is: a = 255 b = 2.5 heat1 = NDSolveValue[{D[u[t, x], t] - (0.0000001 D[u[t, x], x, x] + b*Exp[a *x]) == NeumannValue[0, True] + NeumannValue[-7 (u[t, x] - 25), x == .05], u[0, x] == 25, WhenEvent[ u[t, x] > 250, {a = 0.01*a, b = .2 b, "RestartIntegration"}]}, u, {t, 0, 600}, {x, 0, .05}, Method -> {"MethodOfLines", "TemporalVariable" -> t, "SpatialDiscretization" -> {"FiniteElement", "MeshOptions" -> {"MaxCellMeasure" -> {"Length" -> 0.001}}}}] pa = Plot[Evaluate[heat1[t, 0.05]], {t, 0, 600}, PlotRange -> All, AxesLabel -> {t, "T(.05,t)"}] After running this code, I got the following errors. " NDSolveValue::nbnum1: The function value InterpolatingFunction[{{0.,0.05}},{5,4225,0,{101},{3},0,0,0,0,Automatic,{},{},False},{ >},{25.,25.,25.,25.,...

list manipulation - Listing all monotone increasing binary digits

For $n=5$ , I have $32$ binary digits and for this there are $2^{32}$ combinations. Out of this many, the interesting ones (i.e., the ones that have monotone increasing binary digits) are only about " $2111$ ". I know how these can be found very easily but I am missing Mathematica knowledge. Therefore I cannot complete my program. First I need to seperate these $32$ bits according to Pascals triangle numbers. Since $n=5$ , these numbers are $1,5,10,10,5,1$ . Their sum is $32$ and I separate the digits accordingly. My list is as follows: List={ {0|00000|0000000000|0000000000|00000|0} ... those who satisfy the rule below {1|11111|1111111111|1111111111|11111|1}} From right to the left I start with the 5 bits and take all possible combinations: |00000|--> 00001,00010,00011...11111 This says I have the following ones in the list {0|00000|0000000000|0000000000|00001|1, 0|00000|0000000000|0000000000|00010|1, 0|00000|0000000000|0000000000|00011|1,..., 0|00000|0000000...

parallelization - PrintTemporary in ParallelTable

I thought of a possible answer to Monitor doesn't work with ParallelTable but it doesn't work as I hoped it would. This accumulates print cells instead of deleting them as intended. Can it be fixed? ParallelTable[ NotebookDelete[x]; x = PrintTemporary[i]; Pause[1]; i, {i, 1, 15} ] I thought that x would be local to each kernel, and this would print four cells (for four cores) that would be deleted and replaced with each iteration. I then thought that the value of x was lost between iterations, but this also fails to delete the print cells: ParallelTable[ x = PrintTemporary[i]; NotebookDelete[x]; Pause[1]; i, {i, 1, 15} ] Answer This will display a list that's updated as long as the calculation runs, and vanishes afterwards: (* Pattern that translates the kernel's ID to a number from 1 to $KernelCount *) kernels = ParallelTable[$KernelID -> i, {i, $KernelCount}]; SetSharedVariable[kernels]; (* for Mathematica 7 *) (* This is the list that will disp...

java - Connect to SQLite database

I am trying to connect to a SQLite database and since there is no officially supported driver; I decided to use the sqlite-jdbc driver and port the respective code into Mathematica. However, the DriverManager refuses to connect to the database, the error message is: Java::excptn: A Java exception occurred: java.sql.SQLException: No suitable driver found for jdbc:sqlite:C:/sqlite/test.db at java.sql.DriverManager.getConnection(DriverManager.java:602) at java.sql.DriverManager.getConnection(DriverManager.java:207). The driver & the code that I am trying to port is at: https://bitbucket.org/xerial/sqlite-jdbc and the respective lines that I am having issue is: .... Class.forName("org.sqlite.JDBC"); Connection connection = null; try { // create a database connection connection = DriverManager.getConnection("jdbc:sqlite:sample.db"); .... I noticed the code uses a Class.forName() and I used the JLinkClassLoader to load the same class. Here are my efforts so far: ...

plotting - Histogram based on pre-binned data (center of a bin given) - bin size not equal

I have the following problem. I have a pre-binned list that I want to plot. Here is a shortened example: data:={{16.337, 0}, {18.92, 0}, {21.9105, 0.201491}, {25.374, 0.692208}, {29.3855, 1}, {34.0305, 0.849548}, {39.41, 0.512009}, {45.64, 0.240648}, {52.8545, 0.0905944}, {61.21, 0.0265148}, {70.886, 0.00539223}, {82.0915, 0.000554905}, {95.0685, 0}, {110.097, 0}, {127.501, 0}} The first coordinate refers to the center of the bin and the second one is the count. Typically I would use: ListPlot[data, Joined -> True, InterpolationOrder -> 0, Filling -> Axis] but this creates a histogram where the bins are not centered around the given numbers but rather begin there (as typically done and discussed in other question posts). Due to experimental reasons, the bins' widths increase exponentially, so I cannot just shift all the first coordinates. A possible workaround is to recalculate the beginnings of the bins separately and then feed them into the ListPlot, but I am wondering i...

numerics - Numerical underflow for a scaled error function

I calculate a scaled error function defined as f[x_] := Erfc[x]*Exp[x^2] but it can not calculate f[30000.] . f[20000.] is not very small ( 0.0000282 ). I think Mathematica is supposed to switch to high precision instead of machine precision, but it does not. It says: General::unfl: Underflow occurred in computation. >> General::ovfl: Overflow occurred in computation. >> How can I calculate f for large values of x ? Even with N[f[30000], 50] , it does not use high precision and fails. Answer If you have an analytic formula for f[x_] := Erfc[x]*Exp[x^2] not using Erfc[x] you could do what you expect. However it is somewhat problematic to do in this form because Erfc[x] for x == 27300. $MinNumber 1.887662394852454*10^-323228468 N[Erfc[27280.], 20] 5.680044213569341*10^-323201264 Edit A very good approximation of your function f[x] for values x > 27280 you can get making use of these bounds ( see e.g. Erfc on Mathworld) : which hold for x > 0 . Here we find va...

plotting - Using Inset[..] to overlay a Graphics3D with its raster version

Preamble First let me explain the why . You can skip this and go directly to the question if want to answer it right away. We had more than one discussion about how to produce nice looking 3d plots which can be exported to pdf or some other vector format. Some details why this is not really possible are explained in a post of mine in the question Exporting graphics to PDF - huge file . To solve this issue, there is in my opinion a lot of work to do, since to make it really fancy one would have to reimplement the rendering and 2d-projection process which is done by Mathematica when it displays a Graphics3D . A simple solution, which is maybe OK in a lot of cases, would be to separate the surface of a 3d plot from its box, labels and axes. Then one could create a high-resolution image of the surface and combine this again with the (still in vector format and infinitely high resolved) axes and labels. I showed in the linked post how to do this. To make this working reliable one has to en...

differential equations - Automatic Boundary conditions in NDSolve

I would like to know what kind of boundary conditions Mathematica implements in NDSolve when not specifying any boundary conditions by hand. So for example solving the transport equation: eq = With[{l= 2.}, D[u[t, x], t] + l D[u[t, x], x] == 0]; mol[n_Integer, o_Integer] := {"MethodOfLines", "SpatialDiscretization" -> {"TensorProductGrid", "DifferenceOrder" -> o, "Coordinates" -> N[-1 + 2/n*Range[0, n]]}} solv = NDSolve[{eq, u[0, x] == Exp[-x^2/.1]}, u, {t, 0, 1}, {x, -1, 1}, Method -> mol[51, 4]] Animate[Plot[Evaluate[u[t, x] /. solv], {x, -1, 1}], {t, 0, 1}] This gives me a warning: NDSolve::bcart: Warning: an insufficient number of boundary conditions have been specified for the direction of independent variable x. Artificial boundary effects may be present in the solution. but the equation is still solved. The boundary conditions at $+1$ look like absorbing or periodic boundary conditions but at $-1$ there is something...

debugging - How to find out where an error occurs?

I got this error when using Mathematica : Part::partw: "Part 5 of {{0.637537,0.362463},{0.00038282,0.999617}, {0.0928437,0.907156},{0.0000222833,0.999978}} does not exist." I know why it is generated, but the problem is my code is so lengthy and I cannot find where it comes from. Is there any syntax in Mathematica by which I can resolve my problem? Thanks. Answer Implementation Here is a better version of my debug function posted here , which would print the stack on the first message generated, and abort the computation. I have used it extensively with great effect in many cases. This constructs the nested OpenerView from an arbitrary expression: ClearAll[openerDress]; SetAttributes[openerDress, HoldAll]; openerDress[f_[args___]]:= OpenerView[{ HoldForm[f], HoldForm[f]@@Map[openerDress,Unevaluated[{args}]] }]; openerDress[x_]:=HoldForm[x]; This uses openerDress to represent stack of execution in a way that is expandable when clicked: ClearAll[stackPrettify]; ...

Executing several input cell simultaneously with parallelization

How can I execute more than one input cell simultaneously using different processor. For example consider this two cells Grid[ParallelTable[ContourPlot[Sin[m x] Sin[n y] - Cos[n x] Cos[m y], {x, 0, 2 Pi}, {y, 0, 2 Pi},MaxRecursion -> 5], {m, 2}, {n, 2}]]//TimeUsed T1end=DateString[] and T2begin=DateString[] Grid[ParallelTable[ContourPlot[Sin[m x] Cos[n y] - Cos[m x] Sin[n y], {x, 0, 2 Pi}, {y, 0, 2 Pi},MaxRecursion -> 5], {m, 2}, {n, 2}]]//TimeUsed I hit the shift+enter for the second cell after 3 second of the first one but the execution starts after finishing the first cell and I always get T2begin=T1end . where; T2begin = Starting time of second job (given by DateString[] ) and T1end = Finishing time of first job. What I want is to use half of the processors for the first job and use the aother half for the second job simultaneously (starting from the moment I hit the shift+enter) which will give T2begin , i.e. the second job will start before the completion of first job. (I...

calculus and analysis - Area of surface of revolution

I am asked to rotate the curve $y=\sqrt{4-x^2}$ from $x=-1$ to $x=1$ about the x-axis and find the area of the surface. I was able to use RevolutionPlot3D to show the surface. RevolutionPlot3D[Sqrt[4 - x^2], {x, -1, 1}, RevolutionAxis -> {1, 0, 0}] I used calculus to find the surface area: Integrate[2 π Sqrt[4 - x^2] Sqrt[1 + (-x/Sqrt[4 - x^2])^2], {x, -1, 1}] Which produces the answer $8\pi$. Here is my question. Is there some cute way of finding surface area using Mathematica ; that is, something like using the Area and Volume commands, or some other commands? Answer f[x] == Sqrt[4 - x^2] is the distance at height x from the origin (i.e., from {0, 0} at height x ) to the surface; hence, one can construct reg = ImplicitRegion[z^2 + y^2 == Sqrt[4 - x^2]^2 && -1 which looks like this: DiscretizeRegion[reg] and directly compute Area[reg] $8\pi$ Numerically: Area @ DiscretizeRegion @ reg / Pi 7.99449 in very good agreement. In general this can be applied to any revol...

plotting - Finding all maxima and minima of a function

To find all (global and local) extrema of a function in $\mathbb R^3$ , I have written the following. Example function: n = 2.; terrain[x_, y_] := 2 (2 - x)^2 Exp[-(x^2) - (y + 1)^2] - 15 (x/5 - x^3 - y^3) Exp[-x^2 - y^2] - 1/3 Exp[-(x + 1)^2 - y^2]; fun = terrain[x, y]; plot = Plot3D[fun, {x, -n, n}, {y, -n, n}, PlotRange -> All, ColorFunction -> "DarkTerrain", Mesh -> False, PlotStyle -> Opacity@0.7] One can observe 3 maxima and 3 minima. NMaximize[fun, {x, y}] {6.4547, {x -> -0.3593, y -> -0.5519}} And FindMaximum[fun, {x, y}] {6.1972, {x -> -0.0529, y -> 1.2130}} returns two of the maxima, but misses the third. My idea then was to map NMaximize over "sufficient sectors" of the function: p = Flatten /@ Tuples[Partition[Range[-n, n], 2, 1], 2] {{-2., -1., -2., -1.}, {-2., -1., -1., 0.}, ... , {1., 2., 1., 2.}} (This algorithm was kindly provided by Kuba) The next steps are: max1 = NMaximize[{fun, p[[#, 1]] ...