chi square table in mathematica - wolfram-mathematica

I wanted to calculate the probability associated to a given chi-squared value for any given number of degrees of freedom k. I could easily come up with this code:
P[chisquare_, k_] = Manipulate[NIntegrate[PDF[ChiSquareDistribution[k], x], {x, chisquare, Infinity}], {chisquare, 0, 10}, {k, 1, 10}]
but I was wondering: is there any way to do the opposite? I mean having the probability P as an input and getting the associated chi squared value? like if I wanted to compile a chi-squared table such as this https://www.medcalc.org/manual/chi-square-table.php
I tried using Solve but did not accomplish anything, is there an easy way around this?

You can do the integration with CFD and reverse with Quantile, e.g.
NIntegrate[PDF[ChiSquareDistribution[2], a], {a, 0, 3.0}]
0.77687
p = CDF[ChiSquareDistribution[2], 3.0]
0.77687
Quantile[ChiSquareDistribution[2], p]
Re. your link
Quantile[ChiSquareDistribution[2], 1 - #] & /# {0.995, 0.975, 0.20, 0.10, 0.05};
SetPrecision[#, If[# < 1, 3, 4]] & /# %
{0.0100, 0.0506, 3.219, 4.605, 5.991}

Related

How to find the location of the highest element in a tensor in mathematica

I have a very large array of numbers in the form of a third order tensor.I want to find the highest of all the values in that tensor. How can I do it in mathematica? The context is that a reaction is carried out by varying temperature pressure and vessel volume. I want to find the optimum combination of the three to maximize the product. Each element of the tensor represents a value of the product produced corresponding to a specific combination of temperature pressure and volume.
Given some matrix, tensor, or basically any list-of-lists of real numbers, you can simply use the Max function to determine the maximum value and then Position to say where it is. Assuming your data isn't enormous (requiring some conservative/careful approach to save time/memory), this should be fine.
For example, here is a random list of lists of of lists of reals:
data = Table[RandomReal[],
{i, 1, RandomInteger[{4, 8}]},
{j, 1, RandomInteger[{4, 8}]},
{k, 1, RandomInteger[{4, 8}]}
];
You can just do:
m = Max[data]
Position[data, m]
This will tell you the position of the maximum value. If you did random integers instead, you could have ties, in which case you might have repeats:
data = Table[RandomInteger[{1, 10}],
{i, 1, RandomInteger[{4, 8}]},
{j, 1, RandomInteger[{4, 8}]},
{k, 1, RandomInteger[{4, 8}]}
];
m = Max[data]
Position[data, m]
Table[RandomInteger[100, 3], 3]
Prepend[Ordering[%[[First[Ordering[Reverse#*Sort /# %, -1]]]], -1],
First[Ordering[Reverse#*Sort /# %, -1]]]
% stands for the tensor to sort, in this case it's a random tensor generated from Table[RandomInteger[100, 3], 3]
This gives the position and value in one shot.
(m = RandomReal[{-1, 1}, {4, 3, 2}]) // MatrixForm
First#MaximalBy[
Flatten[MapIndexed[ {##} &, #, {-1}], ArrayDepth[#] - 1],
First] &#m
{0.903213, {3, 2, 2}}
Here is an alternate that will work with ragged lists:
Module[{h},
First#MaximalBy[List ### Flatten[MapIndexed[h### &, #, {-1}]],
First]] &#{{1, 2, 3}, {4, 5, {2, 3}}}
{5, {2, 2}}

Constructing a triadiagonal matrix in Mathematica where nonzero elements contain functions and variables

Suppose I want to construct a matrix A such that A[[i,i]]=f[x_,y_]+d[i], A[[i,i+1]]=u[i], A[[i+1,i]]=l[i], i=1,N . Say, f[x_,y_]=x^2+y^2.
How can I code this in Mathematica?
Additionally, if I want to integrate the first diagonal element of A, i.e. A[[1,1]] over x and y, both running from 0 to 1, how can I do that?
In[1]:= n = 4;
f[x_, y_] := x^2 + y^2;
A = Normal[SparseArray[{
{i_,i_}/;i>1 -> f[x,y]+ d[i],
{i_,j_}/;j-i==1 -> u[i],
{i_,j_}/;i-j==1 -> l[i-1],
{1, 1} -> Integrate[f[x,y]+d[1], {x,0,1}, {y,0,1}]},
{n, n}]]
Out[3]= {{2/3+d[1], l[1], 0, 0},
{u[1], x^2+y^2+ d[2], l[2], 0},
{0, u[2], x^2+y^2+d[3], l[3]},
{0, 0, u[3], x^2+y^2+d[4]}}
Band is tailored specifically for this:
myTridiagonalMatrix#n_Integer?Positive :=
SparseArray[
{ Band#{1, 1} -> f[x, y] + Array[d, n]
, Band#{1, 2} -> Array[u, n - 1]
, Band#{2, 1} -> Array[l, n - 1]}
, {n, n}]
Check it out (no need to define f, d, u, l):
myTridiagonalMatrix#5 // MatrixForm
Note that MatrixForm should not be part of a definition. For example, it's a bad idea to set A = (something) // MatrixForm. You will get a MatrixForm object instead of a table (= array of arrays) or a sparse array, and its only purpose is to be pretty-printed in FrontEnd. Trying to use MatrixForm in calculations will yield errors and will lead to unnecessary confusion.
Integrating the element at {1, 1}:
myTridiagonalMatrixWithFirstDiagonalElementIntegrated#n_Integer?Positive :=
MapAt[
Integrate[#, {x, 0, 1}, {y, 0, 1}]&
, myTridiagonalMatrix#n
, {1, 1}]
You may check it out without defining f or d, as well:
myTridiagonalMatrixWithFirstDiagonalElementIntegrated#5
The latter operation, however, looks suspicious. For example, it does not leave your matrix (or its corresponding linear system) invariant w.r.t. reasonable transformations. (This operation does not even preserve linearity of matrices.) You probably don't want to do it.
Comment on comment above: there's no need to define A[x_, y_] := … to Integrate[A[[1,1]], {x,0,1}, {y,0,1}]. Note that A[[1,1]] is totally different from A[1, 1]: the former is Part[A, 1, 1] which is a certain element of table A. A[1, 1] is a different expression: if A is some table then A[1, 1] is (that table)[1, 1], which is a valid expression but is normally considered meaningless.

Generate terms of an m-order power series in n variables

Consider a situation where you have data in a list of the form
data = {{x1, x2, x3, ..., xn, y}, {...}, ..., {...}}
For example,
data = {{0, 2, 3, 2}, {0, 0, 1, 4}, {7, 6, 8, 3}}
I'd like to fit the data to a multivariate polynomial of order, say, 2.
So, the 3-variable function values are:
{2, 4, 3}
in respective points
{{0, 2, 3}, {0, 0, 1}, {7, 6, 8}}
I'd say something like
Fit[data, {1, x, y, z, x^2, y^2, z^2, x y , x z, y z}, {x, y, z}]
This is all very nice, but i may not have only 3-variate data, there may be an arbitrary number of variables, and I don't know how to programmatically generate all the linear, quadratic or even higher-order terms, to insert them as the second argument of Fit[].
For 4-variate date do second order, it would be something like:
{1, x1, x2, x3, x4, x1^2, x2^2, x3^2, x4^2, x1 x2, x1 x3, x1 x4, x2 x3, x2 x4, x3 x4}
Is there any way I can generate such a list for n variables, to m-th order?
Like terms (without coefficients) in a m-order power series expansion of an n-variable function.
Does this do what you want?
Union[Times ### Tuples[{1, x, y, z}, 2]]
While the solution of #ruebenko is perfectly correct, I'd like to mention that it will be quite slow for higher powers / larger number of variables, because of the complexity of Tuples and lots of duplicates for higher powers. Here is an algebraic method with a much better performance for those cases (both run-time and memory-wise):
List ## Expand[(1 + x + y + z + t)^2] /. a_Integer*b_ :> b
Here is a comparison for large number of variables:
In[257]:= (res1=Union[Times###Tuples[{1,x,y,z,t},9]])//Short//Timing
Out[257]= {19.345,{1,t,t^2,t^3,t^4,t^5,t^6,t^7,t^8,t^9,x,<<694>>,x^2 z^7,y z^7,
t y z^7,x y z^7,y^2 z^7,z^8,t z^8,x z^8,y z^8,z^9}}
In[259]:= (res2=List##Expand[(1+x+y+z+t)^9]/. a_Integer*b_:>b)//Short//Timing
Out[259]= {0.016,{1,t,t^2,t^3,t^4,t^5,t^6,t^7,t^8,t^9,x,<<694>>,x^2 z^7,y z^7,
t y z^7,x y z^7,y^2 z^7,z^8,t z^8,x z^8,y z^8,z^9}}
In[260]:= res1===res2
Out[260]= True
In this case, we observe a 1000x speedup, but generally the two methods just have different computational complexities. The above code is an application of a general and nice method, called Algebraic Programming. For an interesting discussion of it in the context of Mathematica, see this Mathematica Journal paper by Andrzej Kozlowski.
Using #ruebenko's neat solution,
varsList[y_, n_?IntegerQ, k_?IntegerQ] :=
Union[Times ###
Tuples[Prepend[Table[Subscript[y, i], {i, 1, n}], 1], k]]
you can generate desired list via varsList[x, 4, 2].
Here is another method that I believe is worth knowing:
set = {1, x, y, z};
Union ## Outer[Times, set, set]

Mathematica: How to obtain data points plotted by plot command?

When plotting a function using Plot, I would like to obtain the set of data points plotted by the Plot command.
For instance, how can I obtain the list of points {t,f} Plot uses in the following simple example?
f = Sin[t]
Plot[f, {t, 0, 10}]
I tried using a method of appending values to a list, shown on page 4 of Numerical1.ps (Numerical Computation in Mathematica) by Jerry B. Keiper, http://library.wolfram.com/infocenter/Conferences/4687/ as follows:
f = Sin[t]
flist={}
Plot[f, {t, 0, 10}, AppendTo[flist,{t,f[t]}]]
but generate error messages no matter what I try.
Any suggestions would be greatly appreciated.
f = Sin[t];
plot = Plot[f, {t, 0, 10}]
One way to extract points is as follows:
points = Cases[
Cases[InputForm[plot], Line[___],
Infinity], {_?NumericQ, _?NumericQ}, Infinity];
ListPlot to 'take a look'
ListPlot[points]
giving the following:
EDIT
Brett Champion has pointed out that InputForm is superfluous.
ListPlot#Cases[
Cases[plot, Line[___], Infinity], {_?NumericQ, _?NumericQ},
Infinity]
will work.
It is also possible to paste in the plot graphic, and this is sometimes useful. If,say, I create a ListPlot of external data and then mislay the data file (so that I only have access to the generated graphic), I may regenerate the data by selecting the graphic cell bracket,copy and paste:
ListPlot#Transpose[{Range[10], 4 Range[10]}]
points = Cases[
Cases[** Paste_Grphic _Here **, Point[___],
Infinity], {_?NumericQ, _?NumericQ}, Infinity]
Edit 2.
I should also have cross-referenced and acknowledged this very nice answer by Yaroslav Bulatov.
Edit 3
Brett Champion has not only pointed out that FullForm is superfluous, but that in cases where a GraphicsComplex is generated, applying Normal will convert the complex into primitives. This can be very useful.
For example:
lp = ListPlot[Transpose[{Range[10], Range[10]}],
Filling -> Bottom]; Cases[
Cases[Normal#lp, Point[___],
Infinity], {_?NumericQ, _?NumericQ}, Infinity]
gives (correctly)
{{1., 1.}, {2., 2.}, {3., 3.}, {4., 4.}, {5., 5.}, {6., 6.}, {7.,
7.}, {8., 8.}, {9., 9.}, {10., 10.}}
Thanks to Brett Champion.
Finally, a neater way of using the general approach given in this answer, which I found here
The OP problem, in terms of a ListPlot, may be obtained as follows:
ListPlot#Cases[g, x_Line :> First#x, Infinity]
Edit 4
Even simpler
ListPlot#Cases[plot, Line[{x__}] -> x, Infinity]
or
ListPlot#Cases[** Paste_Grphic _Here **, Line[{x__}] -> x, Infinity]
or
ListPlot#plot[[1, 1, 3, 2, 1]]
This evaluates to True
plot[[1, 1, 3, 2, 1]] == Cases[plot, Line[{x__}] -> x, Infinity]
One way is to use EvaluationMonitor option with Reap and Sow, for example
In[4]:=
(points = Reap[Plot[Sin[x],{x,0,4Pi},EvaluationMonitor:>Sow[{x,Sin[x]}]]][[2,1]])//Short
Out[4]//Short= {{2.56457*10^-7,2.56457*10^-7},<<699>>,{12.5621,-<<21>>}}
In addition to the methods mentioned in Leonid's answer and my follow-up comment, to track plotting progress of slow functions in real time to see what's happening you could do the following (using the example of this recent question):
(* CPU intensive function *)
LogNormalStableCDF[{alpha_, beta_, gamma_, sigma_, delta_}, x_] :=
Block[{u},
NExpectation[
CDF[StableDistribution[alpha, beta, gamma, sigma], (x - delta)/u],
u \[Distributed] LogNormalDistribution[Log[gamma], sigma]]]
(* real time tracking of plot process *)
res = {};
ListLinePlot[res // Sort, Mesh -> All] // Dynamic
Plot[(AppendTo[res, {x, #}]; #) &#
LogNormalStableCDF[{1.5, 1, 1, 0.5, 1}, x], {x, -4, 6},
PlotRange -> All, PlotPoints -> 10, MaxRecursion -> 4]
etc.
Here is a very efficient way to get all the data points:
{plot, {points}} = Reap # Plot[Last#Sow#{x, Sin[x]}, {x, 0, 4 Pi}]
Based on the answer of Sjoerd C. de Vries, I've now written the following code which automates a plot preview (tested on Mathematica 8):
pairs[x_, y_List]:={x, #}& /# y
pairs[x_, y_]:={x, y}
condtranspose[x:{{_List ..}..}]:=Transpose # x
condtranspose[x_]:=x
Protect[SaveData]
MonitorPlot[f_, range_, options: OptionsPattern[]]:=
Module[{data={}, plot},
Module[{tmp=#},
If[FilterRules[{options},SaveData]!={},
ReleaseHold[Hold[SaveData=condtranspose[data]]/.FilterRules[{options},SaveData]];tmp]]&#
Monitor[Plot[(data=Union[data, {pairs[range[[1]], #]}]; #)& # f, range,
Evaluate[FilterRules[{options}, Options[Plot]]]],
plot=ListLinePlot[condtranspose[data], Mesh->All,
FilterRules[{options}, Options[ListLinePlot]]];
Show[plot, Module[{yrange=Options[plot, PlotRange][[1,2,2]]},
Graphics[Line[{{range[[1]], yrange[[1]]}, {range[[1]], yrange[[2]]}}]]]]]]
SetAttributes[MonitorPlot, HoldAll]
In addition to showing the progress of the plot, it also marks the x position where it currently calculates.
The main problem is that for multiple plots, Mathematica applies the same plot style for all curves in the final plot (interestingly, it doesn't on the temporary plots).
To get the data produced into the variable dest, use the option SaveData:>dest
Just another way, possibly implementation dependent:
ListPlot#Flatten[
Plot[Tan#t, {t, 0, 10}] /. Graphics[{{___, {_, y__}}}, ___] -> {y} /. Line -> List
, 2]
Just look into structure of plot (for different type of plots there would be a little bit different structure) and use something like that:
plt = Plot[Sin[x], {x, 0, 1}];
lstpoint = plt[[1, 1, 3, 2, 1]];

Using Mathematica to generate crystal lattices

How do you generate a 3x3x3 lattice in Mathematica? Is it possible to color some of the lattice points? It seems that it is possible but I cannot get it to work so far
http://reference.wolfram.com/mathematica/ref/LatticeData.html
What I mean by 3x3x3 is something like figure (c) on the right:http://physics.ucsd.edu/was-sdphul/labs/2dl/exp6/exp63.gif
Must agree with Mark that it is not quite clear what you are asking for -- I'll assume it is the figures you are after. Even then, I can't really tell if there are any obvious generalizations from the FCC/BCC stuff.
Anyways, to just replicate the figures, create the lines and points yourself with something like
Gridlines[n_] := With[{s = Range[0, n - 1]},
Join ## (Flatten[#, 1] & /#
NestList[Transpose[#, {3, 1, 2}] &, Outer[List, s, s, s], 2])]
LatticePoints[name_, n_] := Select[
Tuples[Range[-n, n], 3].LatticeData[name, "Basis"],
(And ## ((# >= 0 && # < n) & /# #) &)]
This works for FCC and BCC:
Graphics3D[{
{Red, Sphere[#, 0.1] & /# LatticePoints["FaceCenteredCubic", 3]},
Line[Gridlines[3]]
}, Boxed -> False]

Resources