O
O
Oleg Petrov2017-10-30 13:51:30
Python
Oleg Petrov, 2017-10-30 13:51:30

How can I make the function iterate over only integer x values?

There is a function that is calculated by the formula.
I then pass the result of the function to the differential_evolution function.
But the search includes values ​​like 3.23343343.
How can I make sure that only integer values ​​get into the differential_evolution function?

from scipy.optimize import differential_evolution
import numpy as np
def function2(x):
    res = x[0] * x[1]
    if res < 100:
        with open("генетика.csv", "a") as f:
            f.write(str(x))
            f.write('\t')
            f.write(str(res))
            f.write('\n')
    return res
bounds = [(-5, 5),(-10, 10)]
result = differential_evolution(function2, bounds)
result.x, result.fun
print(result.x, result.fun)

I found a function to check for an integer.
But when I substitute it into my function, differential_evolution throws an error, since the function does not return any value if I supply a non-integer number there.
How can I set it correctly so that only integers get into my function?
Or will the differential_evolution function itself have to be changed? She's huge -700 lines and I'm afraid of her =)
def is_int(x):
    temp = str(x)  # конвертируем в str для проверок

    i = 0  # счетчик
    while i < len(temp):
        if temp[i] == '.':  # проверяем является ли целым / узнаем индекс нуля

            while i + 1 < len(temp):  # пробегаемся по индексам после "."
                if temp[i + 1] != '0':  # если после "." не ноль - не Int
                    return False
                i += 1
            else:
                return True
        i += 1
    else:
        return True  # если "." нет - следовательно Int

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Dugin, 2017-10-30
@Smeilz1

For cases like x = 1.0:

if int(x) == x:
    ...

Because: You can also do this, but this will only work for true integers (int, not float):
if type(x) is int:
    ...

UPD
data = [1.0, 1.23, 2.0, 2.71, 3.0, 3.14]
for x in filter(float.is_integer, data):
    print(x)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question