0

I am currently writing some code to scale vector graphics, but I am having some issues writing the error handling code in Python, particularly in the line that sets scaled_points within scalePoints. The function takes a list of coordinates (as tuples), a viewport size, and a shrink factor, and returns a scaled set of coordinates.

I am trying to avoid division by zero by using if statements within the lambda, but under certain test cases it does not appear to work. For instance, scalePoints([(0.0,1.0)], 300, 10) causes division by zero to occur, but scalePoints([(0.0,0.0)], 300, 10) does not, and I'm not quite sure why this is.

def scalePoints(points, viewport_size, shrink_factor):
    min_x = findMinX(points)
    max_x = findMaxX(points)

    width = max_x - min_x

    scale = (width/viewport_size) * shrink_factor
    scaled_points = list(map(lambda point: (0.0 if point[0] == 0.0 else (point[0]/scale), 0.0 if point[1] == 0.0 else (point[1]/scale)),points))
    return scaled_points
def findMaxX(points):
    xs = list(map(lambda point: point[0], points))
    return max(xs)
def findMinX(points):
    xs = list(map(lambda point: point[0], points))
    return min(xs)

3 Answers3

2

Comparing point[0] and/or point[1] against 0.0 won't protect you from dividing by zero, because those are the numerator, not the denominator.

Try checking the denominator, scale, instead.

scaled_points = list(map(lambda point: (0.0 if scale == 0.0 else (point[0]/scale), 0.0 if scale == 0.0 else (point[1]/scale)),points))
Kevin
  • 74,910
  • 12
  • 133
  • 166
0

Also comparing floats, in whatever expression, requires care. See the link https://stackoverflow.com/a/33024979/7312441

In your case it might help to add something like

scaled_points = list(map(lambda point: (0.0 if math.isclose(point[0], 0.0,rel_tol=1e-5) else (point[0]/scale), 0.0 if math.isclose(point[0], 0.0,rel_tol=1e-5)  else (point[1]/scale)),points))
Thomas Wright
  • 124
  • 2
  • 6
0

Replace your lambda as follows:

lambda point: (point[0]/scale if point[0] else 0.0, point[1]/scale if point[1] else 0.0)

Aaj Kaal
  • 1,205
  • 1
  • 9
  • 8