0

I am using genetic algorithm to optimize something and the binary code is used for encoding variables.

When the varibles represented a sequence of binary numbers were decoded as its corresponding values, the error (ValueError: invalid literal for int() with base 2: '1.0' was return)

Specifically,

child = 1.0
V = int(child,2)
ValueError: invalid literal for int() with base 2: '1.0'

Could you please give me some clues how to fix this error?

czy
  • 523
  • 2
  • 4
  • 12
  • Are you sure that `child` is really `1.0` (a float number), not `'1.0'` (a string). Passing a float `1.0` to `int` [should work](https://stackoverflow.com/a/47764450/2745495), but your error says you passed a string `'1.0'`. Which is it? – Gino Mempin May 17 '22 at 03:48
  • I expect if you do `child = int(1.0)` then the rest should work as is. – user3479780 May 17 '22 at 03:49
  • Does this answer your question? [ValueError: invalid literal for int() with base 10: ''](https://stackoverflow.com/questions/1841565/valueerror-invalid-literal-for-int-with-base-10) – Gino Mempin May 17 '22 at 03:50
  • 1
    The documentation from [int()](https://docs.python.org/3/library/functions.html#int) tell you the problem: `"...if base is given, then x must be a string, bytes, or bytearray"`. You are giving it a base. – Mark May 17 '22 at 03:53
  • 1
    @GinoMempin the error clearly states it's a string, I'd believe it over what anybody says. And `int` doesn't work on a string with a decimal point. – Mark Ransom May 17 '22 at 03:58

1 Answers1

1

You can't convert a string with a decimal point to integer. You need to remove the decimal point and everything after it.

child = '1.0'
V = int(child.split('.')[0], 2)
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • Can I ask one more question? '1.0' is like an array in my code. So when I used .split(), it returned the error: 'numpy.ndarray' object has no attribute 'split'. Could you please give me some ideas if there are some similar code in array that can the same thing? – czy May 17 '22 at 04:27
  • @czy maybe instead of `child` you can use `str(child)`. I don't know why you got the error that you did with this new information. – Mark Ransom May 17 '22 at 04:34
  • It's like I first use np.random.uniform() to create a population including several children. As a result, the type of 'child' is 'number. narray'. So I am wondering if there are any similar codes in 'numpy' that could do the same thing as 'split' does. – czy May 17 '22 at 04:58
  • @czy `numpy` is not going to generate numbers in base 2, so I really don't understand what you're trying to do. Maybe your question needs some elaboration. – Mark Ransom May 17 '22 at 05:06