Python complex to float

Python 3 data type conversion

Data type conversion refers to the conversion of one data type from the original type to another through some method. For example, we convert the string «123» to the number 123, which is a data type conversion.

Python supports the conversion between various standard data types, but not any data can be converted. All conversions should comply with «common sense» and should be logically valid. For example, you shouldn’t try to convert a complex type to int, because Python doesn’t know how to convert it.

Summary of data type conversion support

Int Float Bool Complex String Bytes List Tuple Set Dict
Int Y Y N Y Y N N N N
Float Y Y N Y Y N N N N
Bool Y Y Y Y Y Y Y Y Y
Complex Y Y Y Y N N N N N
String Y Y Y Y Y Y Y Y Y
Bytes Y N Y N Y Y Y Y N
List N N N N Y Y Y Y Y
Tuple N N N N Y Y Y Y Y
Set N N N N Y Y Y Y Y
Dict N N N N Y N Y Y Y

Note: Bytes only considers direct conversion

Conversion instance

Convert to int

print(int(1.2)) # float -> int print(int('123')) # string -> int print(int(b'456')) # bytes -> int print('0x%x' % (int.from_bytes(b'456', byteorder='little', signed=True))) print(int(True)) # bool -> int

Convert to float

print(float('1.2')) # string->float print(float(b'3.4')) # bytes -> float print(float(123)) # int->float print(float(False)) # bool->float

Convert to bool

# All types can be converted to bool print(bool(1)) # int->bool print(bool(0.0)) # float->bool print(bool(0 + 0j)) # complex->bool print(bool('')) # String - > bool, empty string is False, others are True print(bool(b'hello')) # Bytes - > bool, null is False, others are True print(bool.from_bytes(b'\x00', byteorder='little')) # bytes->bool print(bool([])) # List - > bool, null is False, others are True print(bool(())) # Tuple - > bool, null is False, others are True print(bool(<>)) # Dict - > bool, null is False, others are True print(bool(set())) # Set - > bool, null is False, others are True

Convert to complex

print(complex(100)) # int->complex print(complex(1.2)) # float->complex print(complex(True)) # bool->complex print(complex('1.2+2.3j')) # string->complex

Convert to string

# All basic types can be converted to string print(b'hello'.decode('utf-8')) # bytes->string print(str(1)) # int->string print(str(1.2)) # float->string print(str(True)) # bool->string print(str(1.2 + 2.3j)) # Complex - > string all others are True print(str(['hello', 100])) # list->string print(str(('hello', 100))) # tuple->string print(str()) # dict->string print(str()) # set->string

Convert to bytes

# Because all types can be converted to string and string can be converted to bytes, all types can be indirectly converted to bytes. # Next, we will only discuss the type directly converted to bytes print('bytes'.center(30, '*')) print(b'\x64') # int to bytes print(int.to_bytes(100, byteorder='big', signed=True, length=2)) # int to bytes print(bool.to_bytes(True, byteorder='big', signed=True, length=2)) # bool to bytes print('hello'.encode(encoding='utf-8')) # string to bytes print(bytes([1, 200, 80, 50])) # list to bytes print(bytes((1, 200, 80, 50))) # tuple to bytes print(bytes()) # set to bytes

Convert to list

print(list("hello")) # string->list print(list(b'hello')) # bytes->list print(list((100, 200, 300))) # tuple->list print(list()) # set->list print(list()) # Dict - > list, only the key value is taken

Convert to tuple

print(tuple("hello")) # string->tuple print(tuple(b"hello")) # bytes->tuple print(tuple([100, 200, 300])) # list->tuple print(tuple()) # set->tuple print(tuple()) # Dict - > tuple, only the key value is taken

Convert to set

print(set("hello")) # string->set print(set(b"hello")) # bytes->set print(set([100, 200, 300])) # list->set # print(set([100, 200, [300, 400]])) # List - > set, the list contains variable data types, and an exception is reported print(set(('name', 'age'))) # tuple->set # print(set(('name', 'age', []))) # Tuple - > set, including variable data types, and an exception is reported print(set()) # Dict - > set, only the key value is taken

Convert to dict

# Method 1: use json conversion. The string format needs to be strictly in accordance with the json format user_str = '' import json print(json.loads(user_str)) # Mode 2. Use eval function conversion. eval has potential safety hazards and is not recommended print(eval(user_str)) # Method 3: use ast.literal_eval import ast print(ast.literal_eval(user_str))
# Method 1. zip is required user_keys = ['name', 'city', 'age'] user_values = ['xiaowang', 'Chengdu', 28] print(dict(zip(user_keys, user_values))) # Mode 2: 2D list user_info = [ ["name", "xiaowang"], ["city", "Chengdu"], ["age", 28] ] print(dict(user_info))

Set — > dict tuple — > dict is the same as list — > dict

Читайте также:  What can be done with html

bytearray ⇋ hex

# hex_str-->bytearray byte_array = bytearray.fromhex("050460000008d40462000007670463") print(byte_array) # bytearray-->hex_str hex_str = byte_array.hex() print(hex_str)
# hex_str-->bytearray byte_array = bytearray.fromhex("05 04 60 00 00 08 d4 04 62 00 00 07 67 04 63") print(byte_array) # bytearray-->hex_str hex_str = byte_array.hex() hex_str_space = " ".join([hex_str[i - 1:i + 1] if i % 2 else "" for i in range(len(hex_str))]).strip() print(hex_str_space)

bytearray ⇋ int

import struct # int-->bytearray bytearray_short = struct.pack("int int_short = struct.unpack("

bytearray ⇋ str

# str-->bytearray byte_array = bytearray("liuyang", encoding='utf-8') print(byte_array) # bytearray-->str st_r = byte_array.decode('utf-8') print(st_r)

appendix

  1. '?' The conversion code corresponds to the conversion code defined by C99_ Bool type. If this type is not available, use char to simulate. In standard mode, it is always represented in one byte.
  2. When attempting to package a non integer with any integer conversion code, if the non integer has __index__() Method calls the method before packing and converts the parameter to an integer. Change in version 3.2: added use for non integer __index__() Method.
  3. The 'N' and 'N' conversion codes are only available for native size (select as default or use '@' byte order characters). For standard sizes, you can use any other integer format suitable for your application.
  4. For 'f','d 'and' e 'conversion codes, the packaged representation will use IEEE 754 binary32, binary64 or binary16 format (corresponding to' f ','d' or 'e' respectively), regardless of the floating-point format used by the platform.
  5. 'P' format characters are only available for native byte order (select as default or use '@' byte order characters). The byte order character '=' selects to use the small end or large end sorting based on the host system. The struct module will not interpret it as a native sort, so the 'P' format will not be available.
  6. IEEE 754 binary16 "half precision" type is in IEEE 754 standard Introduced in the 2008 revision of. It contains one sign bit, five exponential bits and 11 precision bits (10 bits are explicitly stored), which can completely and accurately represent numbers in the approximate range of 6.1e-05 and 6.5e+04. This type is not widely supported by the C compiler: on a typical machine, unsigned short can be used for storage, but it will not be used for mathematical operations. See Wikipedia page half-precision floating-point format Learn more.

Added by peaforabrain on Wed, 10 Nov 2021 17:15:29 +0200

  • Java - 6234
  • Python - 2579
  • Javascript - 2100
  • Database - 1608
  • Linux - 1477
  • Back-end - 1449
  • Front-end - 1432
  • Spring - 1358
  • Algorithm - 1311
  • Android - 1124
  • MySQL - 1040
  • C++ - 1022
  • Programming - 966
  • network - 827
  • data structure - 820
  • Attribute - 785
  • C - 721
  • github - 646
  • less - 645
  • SQL - 639

Источник

Typeerror: can’t convert complex to float

Typeerror can

In this article, we will discuss the possible causes of “TypeError: can’t convert complex to float” , and provide solutions to resolve the error.

A “TypeError: can’t convert complex to float” is a common error that occurs when working with complex numbers in Python. This error occurs when you try to perform a mathematical operation that expects a float but receives a complex number instead.

So first let’s discuss further what is a Typeerror: can’t convert complex to float.

What is Typeerror: can’t convert complex to float?

The error message “TypeError: can’t convert complex to float” indicates that you are trying to perform an operation that requires a real number (a float) on a complex number.

A complex number is a number that has a real part and an imaginary part and is represented as a + bj, where a is the real part and b is the imaginary part, and j is the imaginary unit.

If you try to convert a complex number to a float using a function or method that expects a real number, such as float(), you will get this error.

now let us know why this Typeerror occurs.

Causes of Typeerror: can’t convert complex to float

The common reason for the “TypeError: can’t convert complex to float” occurs is when you try to perform a mathematical operation that expects a float input on a complex number.

Here’s an example code that produces the error:

complex_num = 3 + 4j float_num = float(complex_num)

In this code, you are trying to convert a complex number to a float using the float() function. Since a complex number cannot be represented as a float, Python raises the:

TypeError: can't convert complex to float

Here are the other reasons that cause of TypeError: can’t convert complex to float:

import math x = -5 y = math.sqrt(x) 
  1. Attempting to use the log function from the math library with a complex number:
import math z = 2 + 3j log_z = math.log(z)

In this case, the error occurs because a complex number cannot be converted to a float since a complex number has both real and imaginary parts.

Now let’s fix this Typeerror.

How to fix Typeerror: can’t convert complex to float

To fix this Typeerror you make sure to use the appropriate data type for the operation you are performing. If you need to perform mathematical operations on complex numbers, use functions and operations that are specifically designed for complex numbers.

Here are the alternative solutions to fix this Typeerror:

Use the cmath module instead of the math module when working with complex numbers.

import cmath x = complex(2, 3) y = cmath.sqrt(x)

In this code, we import the cmath module and use the cmath.sqrt() function to take the square root of the complex number x . This function is specifically designed to work with complex numbers and will not trigger the TypeError.

The numpy module is a popular library for scientific computing in Python. It provides many functions for working with complex numbers.

import numpy as np x = np.complex(2, 3) y = np.sqrt(x)

In this code, we import the numpy module and use the np.complex() function to create a complex number x . Then we use the np.sqrt() function to take the square root of x . This function is designed to work with both real and complex numbers, so it will not trigger the TypeError.

To extract the real and imaginary parts of a complex number, you can use the real and imag attributes.

goCopy codex = complex(2, 3) y = x.real z = x.imag 

In this code, we create a complex number x . Then we use the real attribute to extract the real part of x and assign it to the variable y , and the imag attribute to extract the imaginary part of x and assign it to the variable z . These attributes return floats, so they will not trigger the “TypeError: can’t convert complex to float” error.

Conclusion

In conclusion, the article Typeerror: can’t convert complex to float is an error message that occurs when you are trying to perform an operation that requires a real number (a float) on a complex number.

By following the given solution, surely you can fix the error quickly and proceed to your coding project again.

If you have any questions or suggestions, please leave a comment below. For more attributeerror tutorials in Python, visit our website.

Leave a Comment Cancel reply

You must be logged in to post a comment.

Источник

Оцените статью