Exploring Numeric Data in Python: Integers, Floats, and Operations
Tags: python, tutorial, productivity, programming
Published: 2024-01-05 18:10:57

## Introduction

Happy new year everyone! I hope you all had a great holiday season and are ready to get back into the swing of things. Today we're going to be exploring numeric data types and operations in Python. Numeric data types like integers, floats, and complex numbers are built-in foundations of Python. This article will dive into how they work at a fundamental level. We'll cover the various numeric types, operations, advanced features like arbitrary precision decimals, and several real-world examples.

## Integers

In Python, an integer is a whole number. It can be either positive or negative, but it must be a whole number. Python supports two types of integers: signed and unsigned. Signed integers are used to represent numbers that can be positive, negative, or zero. The most common data type for signed integers is `int`. For example: ``` x = 10 y = -20 z = 0 ``` Unsigned integers are used to represent numbers that are always positive. The most common data type for unsigned integers is `unsigned int`. For example: ``` a = 1000 b = 4294967295 ``` Python also has a data type called `long` which can represent very large integers.

However, this data type is deprecated and you should use `int64` or `int32` instead. Integers can be used in arithmetic operations, such as addition, subtraction, multiplication, and division. When dividing two integers, the result is always an integer. For example:

```python
x = 10 
y = 2 
result = x / y 
print(result) # Output: 5 
```

Integers can also be used in modulo operations, which returns the remainder of a division. For example:

```python
x = 10 
y = 2 
result = x % y 
print(result) # Output: 0 
```

## Floats

In Python, a float is a decimal number. It can be either positive or negative, and it can have a fractional part. The most common data type for floats is `float`. For example:

```python
x = 10.5 
y = -2.3 
z = 0.0 
```

Python also has a data type called `double` which can represent very large or very small floating-point numbers. However, this data type is deprecated and you should use `float64` or `float32` instead. Floats can be used in arithmetic operations, such as addition, subtraction, multiplication, and division. When dividing two floats, the result is always a float. For example:

```python
x = 10.5 
y = 2.3 
result = x / y 
print(result) # Output: 4.5 
```

Floats can also be used in exponentiation operations, which raises a number to a power. For example:

```python
x = 10 
y = 2 
result = x ** y 
print(result) 
# Output: 1000 
```

### Precision

In Python, the precision of a float determines the number of decimal places to be displayed. The default precision is 6 decimal places. You can set the precision using the `round()` function. For example:

```python
x = 10.5 
y = 2.3 
result = round(x, 2) 
print(result) # Output: 10.50 
```

In this example, the `round()` function rounds the float `x` to 2 decimal places. You can also set the precision of a float using the `Decimal` module. The `Decimal` module allows you to perform arithmetic operations with arbitrary precision. For example:

```python
from decimal import Decimal 
x = Decimal('10.5') 
y = Decimal('2.3') 
result = x / y 
print(result) # Output: 4.5 
```

In this example, the `Decimal` module is used to perform the division of the floats `x` and `y`. The result is displayed with arbitrary precision. ### Rounding

In Python, you can round a float to a specific number of decimal places using the `round()` function. The `round()` function takes two arguments: the number to be rounded and the number of decimal places to be displayed. For example:

```python
x = 10.5 
y = 2.3 
result = round(x, 2) 
print(result) # Output: 10.50 
```

In this example, the `round()` function rounds the float `x` to 2 decimal places. You can also round a float to a specific number of decimal places using the `Decimal` module. The `Decimal` module allows you to perform arithmetic operations with arbitrary precision. For example:

``` python
from decimal import Decimal 
x = Decimal('10.5') 
y = Decimal('2.3') 
result = round(x / y, 2) 
print(result) # Output: 4.50 
```

In this example, the `round()` function is used to round the result of the division of the floats `x` and `y` to 2 decimal places.

In this section, we explored the precision and rounding of floats in Python. The precision of a float determines the number of decimal places to be displayed, while rounding allows you to round a float to a specific number of decimal places. The `round()` function can be used to round a float to a specific number of decimal places, while the `Decimal` module allows you to perform arithmetic operations with arbitrary precision.

**Benefits of the Decimal module:**

- Avoid rounding errors/information loss from float precision
- Fine-grained control over precision and rounding
- Ideal for financial applications requiring precision.
  
Downside is Decimal is slower than built-in float. Use floats where performance is critical and precision requirements are low.

### Complex Numbers

Complex numbers have a real and imaginary part represented as x + yj. Used in some math/scientific domains.

```python
x = 2 + 3j # complex number

y = 3 + 5j # complex number
```

## Operations

### Addition

In Python, you can perform arithmetic operations on integers and floats. The most common arithmetic operations are addition, subtraction, multiplication, and division. For example: ``` x = 10 y = 2 result = x + y print(result) # Output: 12 ``` In this example, the addition operator (`+`) is used to add the integers `x` and `y`. The result is stored in the variable `result`. You can also perform arithmetic operations on floats. For example:

```python
x = 10.5 
y = 2.3 
result = x + y 
print(result) # Output: 12.8 
```

In this example, the addition operator (`+`) is used to add the floats `x` and `y`. The result is stored in the variable `result`.

You can also perform arithmetic operations on integers and floats. For example:

```python
x = 10 
y = 2.3
result = x + y 
print(result) # Output: 12.3 
```

In this example, the addition operator (`+`) is used to add the integer `x` and the float `y`. The result is stored in the variable `result`.

Lets explore the other arithmetic operations in Python.

#### Subtraction

In Python, you can perform subtraction using the subtraction operator (`-`). For example:

```python
x = 10 
y = 2 
result = x - y 
print(result) # Output: 8 
```

In this example, the subtraction operator (`-`) is used to subtract the integers `x` and `y`. The result is stored in the variable `result`.

You can also perform subtraction on floats. For example:

```python
x = 10.5 y = 2.3
result = x - y
print(result) # Output: 8.2 
```

In this example, the subtraction operator (`-`) is used to subtract the floats `x` and `y`. The result is stored in the variable `result`.

You can also perform subtraction on integers and floats. For example:

```python
x = 10
y = 2.3
result = x - y
print(result) # Output: 7.7 
```

In this example, the subtraction operator (`-`) is used to subtract the integer `x` and the float `y`. The result is stored in the variable `result`.

#### Multiplication

In Python, you can perform multiplication using the multiplication operator (`*`). For example:

```python
x = 10
y = 2
result = x * y)

```

In this example, the multiplication operator (`*`) is used to multiply the floats `x` and `y`. The result is stored in the variable `result`.

You can also perform multiplication on integers and floats. For example:

```python
x = 10
y = 2.3
result = x * y
print(result) # Output: 23.0 
```

In this example, the multiplication operator (`*`) is used to multiply the integer `x` and the float `y`. The result is stored in the variable `result`.

### Exponentiation

In Python, you can perform exponentiation using the exponentiation operator (`**`). For example:

```python
x = 10
y = 2
result = x ** y
print(result) # Output: 100 
```

In this example, the exponentiation operator (`**`) is used to raise the integer `x` to the power of `y`. The result is stored in the variable `result`.

You can also perform exponentiation on floats. For example:

```python
x = 10.5
y = 2.3

result = x ** y
print(result) # Output: 125.0 
```

In this example, the exponentiation operator (`**`) is used to raise the float `x` to the power of `y`. The result is stored in the variable `result`.

## Conversion Between Numeric Types

You can convert between numeric types by typecasting with the intended type:

```python
x = 1.5 # float 
int_x = int(x) # convert float to int

y = 5  
float_y = float(y) # convert int to float

z = 10 + 5j
real_z = float(z) # get just the real part
```

Important notes on conversions:

- Converting a float to integer will truncate the decimal part.
- Converting a large integer to float may lose precision.
- Converting an integer to complex just adds 0j as the imaginary part.
- Converting a complex to float just returns the real part.
- Converting a complex to integer will throw an error.

### Real-World Examples

Here are some examples of how numeric types and operations are used in real programs:

- **Finance applications**: Calculate interest, taxes, currency conversions using arithmetic operations. Decimal provides exact precision.
- **Games**: Use integers or floats to keep track of scores, health, damage, levels gained, etc and do math on them.
- **Scientific applications**: Use complex numbers and high precision floats for computations like simulations, AI, and data analysis.
- **Statistics**: Keep running totals/averages as floats. Do lots of addition, subtraction, and division to reduce data.
- **Graphics**: Use integers or floats for coordinates, sizes, rotations - then do math to place objects on screen.
- **Machine Learning**: Datasets have large arrays of floats for weights, biases, probabilities. Do matrix math on them.
- **Web Development**: Use integers or floats to represent quantities like number of users, number of items in cart, etc. Do math on them to calculate totals, averages, etc.
- **Data Science**: Use floats to represent large datasets and do math on them to reduce data, calculate averages, etc.
- **Embedded Systems**: Use integers or floats to represent sensor data like temperature, humidity, etc. Do math on them to calculate averages, etc.

## Conclusion

In this article, we explored numeric data types and operations in Python in detail. Specifically, we looked at the following:

- Integers - Used to represent whole numbers, comes in signed (positive/negative) and unsigned varieties. Primary integer types are int and long (deprecated).
- Floats - Used to represent decimal numbers with fractional parts. Primary types are float and double (deprecated). Floats maintain decimal points in division and other math operations.
- Arithmetic Operators - Addition (+), subtraction (-), multiplication (*), division (/), and exponentiation (**) operators can be used to perform math operations on integers, floats, or a combination of both.
- Division - Integer division always results in an integer. Float division maintains decimals.
Precision - Float precision determines number of decimal places displayed. Can set precision with round() or Decimal module.
- Rounding - round() function and Decimal module allow rounding floats to specified decimal places.
Decimal Module - Provides arbitrary precision decimal arithmetic when float default precision is insufficient.

Choosing the right types, controlling precision, avoiding unexpected rounding, and learning the quirks of computer arithmetic will help write stable numeric code. Look to modules like NumPy when advancing to more complex arrays and matrix operations.

If you have any questions or feedback, please leave a comment below. You can also reach out to me on [Twitter](https://twitter.com/KenMwaura1). or [LinkedIn](https://www.linkedin.com/in/kennedy-mwaura/) If you found this article helpful feel free to share it with others.

Buy me a coffee [here](https://www.buymeacoffee.com/kenmwaura1).

![next-time](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mthxo12c3pejx4nz6dkq.gif)

## Further Reading

- [Python Numeric Types](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex)
- [Python Decimal Module](https://docs.python.org/3/library/decimal.html)
- [Python Numeric Types Tutorial](https://realpython.com/python-data-types/#numeric-types)