# Properly defining and plotting a function that requires NSolve

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.

Try ?NumericQ and assign the NSolve result to h
h[r_?NumericQ, R_?NumericQ, l_?NumericQ, n_?NumericQ] :=h /. NSolve[ • 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? – M. Winter Sep 24 at 12:37
• I tested it, and it cannot handle the case h[r,1,l,6], as then the NSolve might find no solutions, and [] fails. – M. Winter Sep 24 at 12:44
• 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 ! – Ulrich Neumann Sep 24 at 12:52