The If statement inside FindRoot in the following example is evaluating x<100 to be indeterminate. I'm confused as to why and cannot fix it.
The code is:
myroot := FindRoot[If[x < 100, x, x - 1, x - 2], {x, 0}];
myroot
And the output I get is:
{x -> 2.}
where I would expect to see {x -> 0.}. I am using Mathematica 10.0. Thanks!
The solution is the following piece code:
myroot := FindRoot[If[x < 100, x, x - 1, x - 2], {x, 0}, Evaluated->False]; myroot
FindRoot evaluates the objective function symbolically first which leads to the error of x<100 being indeterminate.
Related
I have a task to solve equation system with FindRoot:
a*x+b*y^2-c*x^2=a-b, a*x^2+b*y^2+b*x-cy=b+c , where a = 10, b = 10, c = 6;
I'm very(!) new to Mathematica and have one day to get to know it.
Any comments on how to solve that equation will be much appreciated!
Thanks!
This starts searching for root at x = 0 and y = 0
eq = {a*x + b*y^2 - c*x^2 == a - b, a*x^2 + b*y^2 + b*x - c*y == b + c}
param = {a -> 10, b -> 10, c -> 6}
result = FindRoot[eq /. param, {x, 0}, {y, 0}]
This only gives you 1 of the two Real solutions. Solve will give you both (and even some solutions with Complex numbers). To test it:
eq /. param /. result
This returns (True, True) so you know you've found the correct root.
To find the solution graphically, use ContourPlot:
ContourPlot[Evaluate[eq /. param], {x, -5, 5}, {y, -5, 5}]
Here is the version with Solve/NSolve
NSolve[{a*x + b*y^2 - c*x^2 == a - b,
a*x^2 + b*y^2 + b*x - c*y == b + c} /. {a -> 10, b -> 10, c -> 6},
{x, y}]
It will give the 4 solutions. If you use Solve instead of NSolve you will have a (large) closed form of each component of each solution.
If you need more digits for the solution, add at the end of the NSolve command the option WorkingPrecision->30 (or any other number of digits. These are quadratics, they can computed to any precision necessary).
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.
Following code returns different values for NExpectation and Expectation.
If I try the same for NormalDistribution[] I get convergence erors for NExpectation (but the final result is still 0 for all of them).
What is causing the problem?
U[x_] := If[x >= 0, Sqrt[x], -Sqrt[-x]]
N[Expectation[U[x], x \[Distributed] NormalDistribution[1, 1]]]
NExpectation[U[x], x \[Distributed] NormalDistribution[1, 1]]
Output:
-0.104154
0.796449
I think it might actually be an Integrate bug.
Let's define your
U[x_] := If[x >= 0, Sqrt[x], -Sqrt[-x]]
and the equivalent
V[x_] := Piecewise[{{Sqrt[x], x >= 0}, {-Sqrt[-x], x < 0}}]
which are equivalent over the reals
FullSimplify[U[x] - V[x], x \[Element] Reals] (* Returns 0 *)
For both U and V, the analytic Expectation command uses the Method option "Integrate" this can be seen by running
Table[Expectation[U[x], x \[Distributed] NormalDistribution[1, 1],
Method -> m], {m, {"Integrate", "Moment", "Sum", "Quantile"}}]
Thus, what it's really doing is the integral
Integrate[U[x] PDF[NormalDistribution[1, 1], x], {x, -Infinity, Infinity}]
which returns
(Sqrt[Pi] (BesselI[-(1/4), 1/4] - 3 BesselI[1/4, 1/4] +
BesselI[3/4, 1/4] - BesselI[5/4, 1/4]))/(4 Sqrt[2] E^(1/4))
The integral for V
Integrate[V[x] PDF[NormalDistribution[1, 1], x], {x, -Infinity, Infinity}]
gives the same answer but multiplied by a factor of 1 + I. This is clearly a bug.
The numerical integral using U or V returns the expected value of 0.796449:
NIntegrate[U[x] PDF[NormalDistribution[1, 1], x], {x, -Infinity, Infinity}]
This is presumably the correct solution.
Edit: The reason that kguler's answer returns the same value for all versions is because the u[x_?NumericQ] definition prevents the analytic integrals from being performed so Expectation is unevaluated and reverts to using NExpectation when asked for its numerical value..
Edit 2:
Breaking down the problem a little bit more, you find
In[1]:= N#Integrate[E^(-(1/2) (-1 + x)^2) Sqrt[x] , {x, 0, Infinity}]
NIntegrate[E^(-(1/2) (-1 + x)^2) Sqrt[x] , {x, 0, Infinity}]
Out[1]= 0. - 0.261075 I
Out[2]= 2.25748
In[3]:= N#Integrate[Sqrt[-x] E^(-(1/2) (-1 + x)^2) , {x, -Infinity, 0}]
NIntegrate[Sqrt[-x] E^(-(1/2) (-1 + x)^2) , {x, -Infinity, 0}]
Out[3]= 0.261075
Out[4]= 0.261075
Over both the ranges, the integrand is real, non-oscillatory with an exponential decay. There should not be any need for imaginary/complex results.
Finally note that the above results hold for Mathematica version 8.0.3.
In version 7, the integrals return 1F1 hypergeometric functions and the analytic result matches the numeric result. So this bug (which is also currently present in Wolfram|Alpha) is a regression.
If you change the argument of your function u to avoid evaluation for non-numeric values all three methods gives the same result:
u[x_?NumericQ] := If[x >= 0, Sqrt[x], -Sqrt[-x]] ;
Expectation[u[x], x \[Distributed] NormalDistribution[1, 1]] // N;
N[Expectation[u[x], x \[Distributed] NormalDistribution[1, 1]]] ;
NExpectation[u[x], x \[Distributed] NormalDistribution[1, 1]];
{% === %% === %%%, %}
with the result
{True, 0.796449}
When using constraints with simple equality in Mathematica 8, minimization doesn't work. E.g.
FindMinimum[{x^2 + y^2, y == 1}, {x, y}]
works ok in Mathematica 6, but gives errors in version 8. Can anyone else confirm (or explain) this? Looks like fixing one of the parameters with a constraint confuses version 8. Putting xy==1 is OK, also any inequality.
Any simple workaround on this? I have tried changing the Method, no luck. I would like to keep all the parameters in the parameter list, but hold some of them with simple constraint instead of removing the parameter name from the list. I have a working code in version 6, which does not work anymore in 8.
Another workaround would be to use version 9.
In[1]:= FindMinimum[{x^2 + y^2, y == 1}, {x, y}]
Out[1]= {1., {x -> 0., y -> 1.}}
Which is to say, what you show above is a bug that has kindly fixed itself for a future release.
Daniel Lichtblau
Wolfram Research
Your syntax appears to be incorrect:
FindMinimum[{x^2 + y^2, y == 1}, {x, y}]
which asks to start x with a value of y. This doesn't make much sense to me.
Perhaps you are attempting to do:
Minimize[{x^2 + y^2, y == 1}, {x, y}]
Out: {1, {x -> 0, y -> 1}}
Apparently your syntax is valid. Consider Minimize as shown above to be a possible work-around for your problem.
In[31]:= NMinimize[{x^2 + y^2, y == 1}, {x, y}]
Out[31]= {1., {x -> -3.20865*10^-9, y -> 1.}}
In[32]:= FindMinimum[{x^2 + y^2, 1 - 10^-10 <= y <= 1 + 10^-10}, {x, y}]
Out[32]= {1., {x -> 0., y -> 1.}}
However, I wonder how to force mma to keep on searching even if it encounters a infinite expression? Can anybody share your idea?
thanks ^_^
I want to use something like:
ContourPlot [Abs[z-1] == 2]
and to define z as being = x + iy
I saw somewhere an example like that with the With function, but I can't find it anymore and all my tries are not being successful.
Yes, you can. You just need to be sure to either put the With outside of the ContourPlot:
With[{z = x + I y},
ContourPlot[Abs[z - 1] == 2, {x, -2, 2}, {y, -2, 2}]]
You can also use Evaluate:
ContourPlot[
With[{z = x + I y}, Abs[z - 1] == 2] // Evaluate, {x, -2, 2}, {y, -2, 2}]
This is generally the case with plotting functions, which almost always evaluate their arguments in a non-standard way.