0
def getpoints(r):
    cx = 0
    rt = int(r*10)
    for i in range(rt*10+1):
        cy = math.sqrt(r**2-cx**2)  #circle formula
        print(cx, cy)
        x.append(cx)
        y.append(cy)
        cx = cx + 0.1

This is part of my code. It is meant to calculate plots on a circle
x at the start gets 0.1 added to it each iteration, but as it goes on it starts to get things like 1.6000000000000003 as the output for x. This causes a problem where, for example r = 2.5 and x = 2.400000000000001, then it adds 0.1 and it tries to square root r^2 - x^2 but x is bigger than r, even though it shouldn't be
By x I mean cx
I have tried math.fabs() which to me seemed like it might work but it didn't.

How do I fix this. It only needs to be accurate to 0 decimal places, just not sqrt negative numbers

I feel like I'm being dumb here

  • If it only needs to be accurate to a certain number of decimal places just round the numbers to that precision. –  Nov 12 '19 at 11:10

1 Answers1

0

To know what is going on, it helps to inspect all variables at the stages of your program, either with the debugger or with via printing out values.

Your problem isn't the accuracy. When your 'r=0.1', then 'r**2=0.01', while you loop cx as 0, 0.1, 0.2, .... So r**2necessarily gets smaller than cx**2 and you're trying to take the sqrt of a negative number.

When r=2.5, r**2=6.25 and your cx goes 0, 0.1, 0.2, ..., 25.0 making cx**2 much larger than r**2.

You should revise your strategy of choosing the range for cx. The easiest way is to forget about the confusing variable i and just check the value of cx:

import math

def getpoints(r):
    x = []
    y = []
    cx = 0
    while cx <= r:
        cy = math.sqrt(r**2-cx**2)  #circle formula
        print(cx, cy)
        x.append(cx)
        y.append(cy)
        cx += 0.1
    return x, y

x_coords, y_coords = getpoints(2.5)

print(x_coords)
print(y_coords)
JohanC
  • 71,591
  • 8
  • 33
  • 66