0
$\begingroup$

I want to defined a function that solves some equation numerically:

h[r_, R_, l_, n_] := NSolve[l^2 == r^2 + R^2 - 2 h^2 - 2 Sqrt[(r^2 - h^2) (R^2 - h^2)] Cos[2 Pi/n] && h >= 0, h, Reals]

I then want to plot this function via

DensityPlot[h[r,1,l,6], {r,0,1}, {l,0,1}]

Of course, this does not work, as NSolve does not return a numeric value, but a list of lists of rules, which might even be empty.

My intention would be to define h in such a way, so that it extracts the desired numerical value (the unique positive solution, if there is one), and otherwise returns, ..., well, no idea actually. What should it return otherwise? What I want in the end, is that DensityPlot works well with that function, so that regions where h is not well-defined are just blank. The region where it is not well-defined are not explicitly known, though.

I thought about defining h so that it returns Indeterminate whenever the list is empty, but then DensityPlot seems to throw $Failure. Also

RegionPlot[h[r,1,l,6] =!= Indeterminate, {r,0,1}, {l,0,1}]

does not to work for showing the region in which h is well-defined.

$\endgroup$

1 Answer 1

1
$\begingroup$

Try ?NumericQ and assign the NSolve result to h

h[r_?NumericQ, R_?NumericQ, l_?NumericQ, n_?NumericQ] :=h /. NSolve[
l^2 == r^2 + R^2 - 2 h^2 -2 Sqrt[(r^2 - h^2) (R^2 - h^2)] Cos[2 Pi/n] && h >= 0, h,Reals][[1]]
DensityPlot[h[r, 1, l, 4], {r, 0, 1}, {l, 0, 1}]

enter image description here

$\endgroup$
3
  • $\begingroup$ Does this also work for h[r,1,l,6]? I will edit the question, as the case with 4 wasn't actually the problematic one. Sorry for this! But in general, how does ?NumericQ solve the issue? $\endgroup$
    – M. Winter
    Sep 24, 2019 at 12:37
  • $\begingroup$ I tested it, and it cannot handle the case h[r,1,l,6], as then the NSolve might find no solutions, and [[1]] fails. $\endgroup$
    – M. Winter
    Sep 24, 2019 at 12:44
  • $\begingroup$ Try ContourPlot3D[ l^2 == 0.0025 - 2 h^2 + r^2 - Sqrt[(0.0025 - h^2) (-h^2 + r^2)], {r, 0, 1}, {l, 0, 1}, {h, 0, 0.05}, AxesLabel -> Automatic] to check the possible solutions ! $\endgroup$ Sep 24, 2019 at 12:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.