0

I am having float point problems using the Shapely library. I realize now, (after reading the instructions) that using pt.wkt will trim the variable therefore, I am changing my code to uses wkt.dumps(pt, Trim = False). I see that str(pt) also trims the results.

Question: Does any other code in Shapely trim the decimals?

pt.x or pt.y or pt.xy sometimes look trimmed but I think this is caused by dumping the coordinates in a Python array. Am I wrong?

Vince
  • 20,017
  • 15
  • 45
  • 64
  • It is not a shapely problem but a more general problem (Floating Point Math) – gene Jun 22 '21 at 20:19
  • I agree for pt.x or pt.y or pt.xy but not for .wkt function. Manual states "The default settings for the wkt attribute and shapely.wkt.dumps() function are different. By default, the attribute’s value is trimmed of excess decimals, while this is not the case for dumps(), though it can be replicated by setting trim=True." I am just wondering if this is the case elsewhere in the library. – Nicolas Cadieux Jun 22 '21 at 21:54

1 Answers1

1

If you look at the docstring of dumps function in the shapely.wkt script

def dumps(ob, trim=False, **kw):
    """
    Dump a WKT representation of a geometry to a string.
    Parameters
    ----------
    ob :
        A geometry object of any type to be dumped to WKT.
    trim : bool, default False
        Remove excess decimals from the WKT.
    rounding_precision : int
        Round output to the specified number of digits.
        Default behavior returns full precision.
    output_dimension : int, default 3
        Force removal of dimensions above the one specified.
    Returns
    -------
    input geometry as WKT string
    """
    return geos.WKTWriter(geos.lgeos, trim=trim, **kw).write(ob)

You can see

  • that trim=False is the default
  • you can set a rounding precision (numpy precision) and an output dimension (for 2D and 3D geometries)

For the other codes that trim the decimals if you do a search for Trim in the shapely code you find

Knowing that Shapely and GEOS cannot reduce precision (floating-point precision problem, How to deal with rounding errors in Shapely, Rounding all coordinates in shapely?) this problem will always exist.

Example :

pt = Point(0.56789, 0.63245)
np.array(pt)
array([0.56789, 0.63245]) #the coordinates are numpy arrays for the computation
pt.x , pt.y
(0.56789, 0.63245)
pt.xy 
(array('d', [0.56789]), array('d', [0.63245]))
pt.wkt
'POINT (0.56789 0.63245)'
wkt.dumps(pt) # trim=False by default
'POINT (0.5678900000000000 0.6324500000000000)'
wkt.dumps(pt, trim=True) # = pt.wkt
'POINT (0.56789 0.63245)'
wkt.dumps(pt, trim=True, rounding_precision=3)
'POINT (0.568 0.632)'
np.round(pt,3)
array([0.568, 0.632])
gene
  • 54,868
  • 3
  • 110
  • 187