Python Forum

Full Version: Rounding issue
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am writing a simple program to calculate the zero point for a function. However it will never find it because of rounding. Any suggestions of how this can be done? Thanks.

def function_g(x):
    return ((2*x)-1)
    
 
counter=-10
while counter<10:
    functionvalue=funksjon_g(counter)
    if functionvalue==0 :
        print("Zero point is ---------------->     " + str(counter))
    
    print("counter is    " + str(counter) +"    "+ str(function_g(counter)))
    counter=counter+0.1
Use
https://docs.python.org/3/library/math.h...th.isclose Wrote:math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
Return True if the values a and b are close to each other and False otherwise.

Whether or not two values are considered close is determined according to given absolute and relative tolerances.

rel_tol is the relative tolerance – it is the maximum allowed difference between a and b, relative to the larger absolute value of a or b. For example, to set a tolerance of 5%, pass rel_tol=0.05. The default tolerance is 1e-09, which assures that the two values are the same within about 9 decimal digits. rel_tol must be greater than zero.

abs_tol is the minimum absolute tolerance – useful for comparisons near zero. abs_tol must be at least zero.

If no errors occur, the result will be: abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol).

The IEEE 754 special values of NaN, inf, and -inf will be handled according to IEEE rules. Specifically, NaN is not considered close to any other value, including NaN. inf and -inf are only considered close to themselves.

New in version 3.5.