# Cannot convert 'nan' to double error when using QGIS field calculator

I am using the formula:

(\$perimeter -sqrt(\$perimeter^2 - 16 * \$area)) /4

to calculate the width of irregular polygons in a layer. However, I get an error

"cannot convert 'nan' to double"

I have looked at other stackoverflow reports on this error but cannot make it run correctly. I have tried changing the output type and the field length with no avail.

• somewhere you are dividing by 0 or taking the sqrt of a negative number or some such issue - try checking the inputs to your equation Oct 21, 2022 at 17:09
• @MrXsquared it is a polygon layer and the \$perimeter and \$area should be inherently calculated from qgis, so they are not calling upon attribute columns (to my understanding). All of the features have valid geometries, so I don't understand how this could be an issue. I don't know how sharing any data would help. Oct 21, 2022 at 17:54
• What other “stackoverflow reports” have you looked at? Please provide links to them within the body of your question.
– PolyGeo
Oct 21, 2022 at 20:18
• just try to calculate this \$perimeter^2 - 16 * \$area and see if there are any negative values Oct 21, 2022 at 20:58
• I managed to reproduce error: if there are polygons similar to circles, the expression \$perimeter ^2 - 16 * \$area is negative !!! Oct 21, 2022 at 21:07

The expression returns the error if there were circles or polygons very similar to circles among the polygons; in fact assuming the presence of a circle:

(2*pi*r)^2 < 16*pi*r^2

pi(4*pi*r^2) < 4(4*pi*r^2)

that is pi < 4

EDIT1:

To prevent the error from appearing you can use the expression:

try(
(\$perimeter -sqrt(\$perimeter^2 - 16 * \$area)) /4
,0)

which will calculate the expression in all polygons except the ones that generate error ((in these polygons, it will always return 0).

EDIT2:

you also need to pay attention to the number of digits after the comma (for the perimeter and area) because the difference \$perimeter^2-16*\$area could be negative, so I also suggest this solution:

with_variable('perim', round(\$perimeter,1),
try(
(@perim-sqrt((@perim)^2 - 16*round(\$area,1)))/4
,0))
• This is great, thank you. I know you said "assuming" presence of a circle. My polygons are definitely not circles (but QGIS thinks they are). Do you know how I could Identify which polygons it thinks are circles and then exclude them from this calculation? Oct 22, 2022 at 14:17
• @hcf, I added a possible solution to the answer to prevent the calculation from freezing. Oct 22, 2022 at 16:14