D
D
DTPlayer2020-07-09 03:26:01
Python
DTPlayer, 2020-07-09 03:26:01

Python how to solve payment issue?

def check_payment(user_id):
    conn = sqlite3.connect('data.db')
    cur = conn.cursor()
    cur.execute('''SELECT qiwi_number FROM config''')
    numb = cur.fetchall()
    QIWI_NUMBER = list(numb[0])[0]
    cur.execute('''SELECT qiwi_token FROM config''')
    to = cur.fetchall()
    QIWI_TOKEN = list(to[0])[0]
    try:
        session = requests.Session()
        session.headers['authorization'] = 'Bearer ' + QIWI_TOKEN
        parameters = {'rows': '5'}
        h = session.get(
            'https://edge.qiwi.com/payment-history/v1/persons/{}/payments'.format(QIWI_NUMBER),
            params=parameters)
        req = json.loads(h.text)
        result = cur.execute(f'SELECT * FROM payment_query WHERE user_id = {user_id}').fetchone()
        comment = str(result[2])
        sum = result[1]
        for i in range(len(req['data'])):
            if comment in str(req['data'][i]['comment']):
                print(round(float(req["data"][i]["sum"]["amount"])))
                print(sum)
                if round(float(req["data"][i]["sum"]["amount"])) == sum:
                    cur.execute(f'UPDATE users SET access = "True" WHERE id = "{user_id}"')
                    conn.commit()

                    cur.execute(f'DELETE FROM payment_query WHERE user_id = "{user_id}"')
                    conn.commit()

                    return 1
    except Exception as e:
        print(e)

    return 0

When doing float and sum are the same values, but they are not equal, why?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Pankov, 2020-07-09
@DTPlayer

When doing float and sum are the same values, but they are not equal, why?

Because it is impossible to compare float for strict equality without taking into account the error.
Not every even rational number can be represented as a finite decimal or binary fraction. For example, 1/3 in decimal is an infinite periodic fraction, and in ternary "0.1". So not every decimal fraction finite in the number of digits can be represented by a final binary fraction. It turns out that the loss of very small fractions of the number associated with the limited accuracy (number of bits) of float depends on the order of calculations.
You need to select an accuracy threshold and compare numbers using it:
EPS = 1e-6
abs(a - b) < EPS

S
Sergey Tikhonov, 2020-07-09
@tumbler

In money, Decimal is usually used - numbers with a fixed point. Floats in practice are more like "real numbers with an error" - i.e. exact equality is an event with zero probability (as opposed to "a and b differ by less than a delta").

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question