Skip to content
Home » Blog » Python for Network Engineers Blog 10: Python Floats

Python for Network Engineers Blog 10: Python Floats

main blog post image for my blog: Python for Network Engineers Blog 10: python floats showing what a float is alongside the python logo

Python Floats – Actually, Let’s Sort This Out Properly

Okay so we’re at python floats now. So we’ve got integers working haven’t we, got variables sorted, print function working, comments are done, you’ve figured out the indentation business.

Python for Network Engineers Blog 9: Python Integers

Now here’s where most Python courses completely lose the plot again. They’ll have you calculating mortgage payments or working out petrol mileage or figuring out how much tip to leave at restaurants. I’m sitting there thinking, that’s lovely mate but I’ve got CPU percentages and bandwidth utilisation to monitor. How’s Dave’s restaurant bill going to help me track interface statistics then?

Thing is, I made this exact mistake when I started. About three years back, kept hearing about this Python stuff from the boss. Thought I’d better get up to speed, so had a look at some online courses. First one I tried, they’re teaching me to calculate compound interest and work out loan repayments. I’m thinking how’s this going to help me automate VLAN configurations then? Complete waste of time.

Few months later, had this monitoring system that kept throwing false alerts because the CPU thresholds were set as integers instead of floats. Half the devices showing “70% CPU” when they were actually at 70.3%, and the monitoring system was rounding everything down. Thought there’s got to be a better way than manually checking every single device and trying to work out what the actual utilisation was.

Found someone who explained it properly using actual network monitoring examples. Made much more sense straight away. Instead of learning about calculating Dave’s mortgage, I’m learning about storing CPU loads and interface utilisation. Instead of working out restaurant tips, I’m working with temperature readings and power consumption.

So let’s do floats properly using network stuff that matters.

What Floats Actually Do

Right so a float in Python, it’s just a decimal number isn’t it. Numbers with decimal points. Could be positive, negative, zero, doesn’t matter.

Let me show you what I mean. Let’s get cracking with some proper examples:

cpu_usage = 23.7
temperature = 45.2
bandwidth_util = 67.8

There we go. See? Actual networking numbers. Not how much Dave spent on his weekly shopping.

Now here’s something quite clever about floats that I didn’t appreciate when I started. Python floats are what’s called “double precision” floating point numbers. That means they can handle really precise decimal calculations.

Actually, let me tell you what happened last month. Working with some QoS calculations that needed precise bandwidth allocations. Fractions of percentages, tiny decimal values. I was worried Python wouldn’t handle the precision properly, but it just sorted it out without me having to worry about rounding errors or precision loss. Brilliant really.

Thing is, most programming languages make you worry about different float sizes and precision levels. Pain in the backside. Python just says forget all that nonsense. Float’s a float, it’ll be as precise as you need.

Why This Matters for Network Engineers

Look, networking’s absolutely stuffed with decimal measurements, right? CPU percentages, bandwidth utilisation, temperature readings, power consumption, response times. Everything that gets monitored produces decimal values.

Understanding floats properly means you can work with all this measurement data without constantly converting between different number formats. Makes your monitoring scripts much cleaner.

Let me show you:

cpu_threshold = 85.0
current_cpu = 67.3
temperature_limit = 55.5
current_temp = 48.7

These are floats because they represent actual measured values that can be anywhere between whole numbers. Can’t have exactly 23% CPU usage can you? It’s always going to be something like 23.7% or 22.9%.

But here’s where people get confused, and I made this mistake early on. When should network measurements be floats versus integers?

When to Use Floats vs Integers for Network Data

This catches people out constantly. I was having a chat with a mate last week who’d been struggling with this exact problem.

Simple rule I use. If it’s a measurement that can have decimal places, make it a float. If it’s a count of discrete things, keep it as an integer.

Let me work through this:

cpu_usage = 23.7        # Float - measured percentage
vlan_id = 10           # Integer - discrete identifier
response_time = 1.234   # Float - measured time
port_count = 24        # Integer - count of things

So cpu_usage = 23.7 as a float because CPU usage is a measured percentage that changes continuously. But vlan_id = 10 as an integer because VLAN IDs are discrete identifiers. Can’t have VLAN 10.5 can you? Doesn’t make sense.

image showing python floats vs python intergers

Got caught out by this early on actually. Had a script that was storing CPU percentages as integers, couldn’t work out why all my monitoring was showing 23% instead of 23.7%. The decimal part was getting chopped off. Spent ages debugging before I realised I was losing the precision. Felt like a right pillock.

Actually, let me tell you the full story because it gets worse. This was about two years back, right? Had this monitoring setup that was supposed to alert when CPU went above 85%. But I’d stored everything as integers, so 85.3% CPU was showing as 85%, which didn’t trigger the alert. Then the device hit 89% actual usage, but my script thought it was still at 85%. Device nearly overheated before I spotted the problem manually.

The key thing is thinking about what you’re actually going to do with the data. Measurements and calculations need floats. Counts and identifiers can stay as integers.

Different Number Systems We Actually Use

Right so here’s something that confused the hell out of me when I started. Network monitoring produces floats in loads of different formats, but Python needs to understand which one you mean.

Decimal’s what you’re used to. Normal counting, base 10. That’s Python’s default. cpu_usage = 23.7, temperature = 45.2. Nothing special there.

But monitoring systems use other representations constantly don’t they? Let me show you the main ones:

Scientific notation shows up everywhere with big bandwidth numbers. Link speeds, packet rates, that sort of thing. Python handles scientific notation with e in the middle.

link_speed = 1e9        # 1 gigabit in bits per second
packet_rate = 2.5e6     # 2.5 million packets per second
latency = 1.5e-3        # 1.5 milliseconds

The e means “times ten to the power of”. So 1e9 is 1 × 10^9, which is 1,000,000,000. Much easier to write than nine zeros.

Had this come up recently actually. Working with some throughput calculations that involved enormous packet rates. Without scientific notation, I’d have been writing numbers with loads of zeros everywhere. Scientific notation kept the numbers manageable in the code while still representing the actual values accurately.

Don’t see binary much with floats, but you’ll run into scientific notation constantly when you’re parsing monitoring data or working with high-speed interface statistics.

The important bit is Python can handle all these different formats, so when you’re working with monitoring data that uses different representations, Python sorts it out for you. Great stuff.

Working with Float Variables

Let me tell you about mistakes I see people make constantly when working with floats. Made most of these myself at some point, which is how I know they’re coming.

Keep it simple when creating variables. If you know it’s a decimal measurement, just assign it:

cpu_load = 45.7
temp_reading = 52.3

Don’t do daft things like cpu_load = float(“45.7”). Why convert from string if you already know it’s the number 45.7?

Python floats work perfectly for network calculations:

total_bandwidth = 1000.0    # Mbps
used_bandwidth = 234.5      # Mbps
available_bandwidth = total_bandwidth - used_bandwidth
utilisation = (used_bandwidth / total_bandwidth) * 100

Basic arithmetic that actually means something for capacity planning.

But here’s where it gets tricky, and this is something that caught me out last year. Float comparisons need a bit of care. Because of how computers store decimal numbers, sometimes you get tiny rounding differences that you can’t see.

# This might not work as expected
if cpu_usage == 23.7:
    print("Exactly 23.7%")

# Better approach for thresholds
if cpu_usage > 85.0:
    print("High CPU usage")

For monitoring, you’re usually checking thresholds anyway, so exact equality comparisons don’t come up much. But worth knowing about because it’ll bite you eventually if you try doing exact comparisons with calculated values.

Actually, let me show you what happened to me. Had this script that was supposed to detect when bandwidth utilisation hit exactly 50.0%. The calculation was giving me 49.99999999999999 instead of 50.0, so the condition never triggered. Took me ages to work out why the script wasn’t working. Now I always use greater than or less than comparisons for thresholds.

Mistakes Everyone Makes

Right, let me tell you about cock-ups I see repeatedly. Made most of these myself when I was learning, which is probably why I notice them so easily now.

Big one is treating measurements as text. Storing decimal measurements as strings then trying to calculate with them.

Let me show you what I mean:

# Wrong
cpu_1 = "23.7"
cpu_2 = "45.2"
average = (cpu_1 + cpu_2) / 2  # Error - can't do maths on strings

That’ll give you an error because you’re trying to add strings together, not numbers. What you get is “23.745.2” instead of adding the values.

# Right
cpu_1 = 23.7
cpu_2 = 45.2
average = (cpu_1 + cpu_2) / 2  # Gets 34.45

There we go. That’s better.

Happens because monitoring systems sometimes export data as CSV or text files. Everything comes out as strings even if it represents numbers. Need to convert before doing calculations.

The input() function always returns strings, even if the user types a number. Need to convert before doing maths. user_threshold = input(“CPU threshold: “), then cpu_threshold = float(user_threshold).

Not handling bad input properly bit me badly once. User entered rubbish, monitoring script crashed during a network outage. Proper embarrassing that was. Boss wasn’t best pleased when the monitoring went down during an incident.

Always use try/except when converting strings to floats:

try:
    cpu_reading = float(raw_data)
    if cpu_reading > 85.0:
        send_alert()
except ValueError:
    print("Invalid CPU reading")

If the conversion fails, handle it gracefully instead of letting your script explode.

Code editor screenshot showing common python floats mistakes with error messages, demonstrating string concatenation vs float calculations and precision issues

Python floats have limited precision. For most network monitoring, this doesn’t matter, but worth knowing about.

# This might not be exactly what you expect
result = 0.1 + 0.2  # Could be 0.30000000000000004

# For monitoring thresholds, round to sensible precision
cpu_usage = round(23.7234, 1)  # Gets 23.7

In practice, monitoring data already comes rounded to sensible precision, so you don’t usually hit this problem. But if you’re doing lots of calculations, sometimes the tiny rounding errors accumulate.

Actually, let me tell you about a time this caught me out. Working on some bandwidth calculations, adding up lots of small decimal values. After about fifty calculations, the result was off by 0.001%, which doesn’t sound like much, but when you’re working with gigabit links, that’s still a fair bit of bandwidth. Had to add rounding to get sensible results.

Actually Useful Applications

Once you get python floats sorted, loads of monitoring tasks become much easier. Let me show you some proper examples.

For threshold monitoring, define your warning and critical levels once then reference them throughout your scripts:

cpu_warning = 70.0
cpu_critical = 85.0
temp_warning = 50.0
temp_critical = 60.0

Then you can check if current_cpu > cpu_critical and send alerts accordingly. Brilliant for keeping all your thresholds in one place.

Capacity planning becomes straightforward:

current_util = 67.8
monthly_growth = 2.3  # Percent per month
months_to_capacity = (95.0 - current_util) / monthly_growth

Work out when you’ll hit capacity limits based on current trends. Really useful for planning upgrades.

Basic performance calculations:

total_requests = 10000
response_time_sum = 2345.67  # seconds
average_response = response_time_sum / total_requests

This kind of calculation comes up constantly when you’re analysing network performance.

Actually, let me tell you about a project where this really helped. Had to analyse performance across twenty WAN links, needed to work out which ones were degrading. Without proper float handling, all the latency measurements would have been useless. With floats, could spot trends and identify problem links before users started complaining.

Converting Between Data Types

Sometimes you need to convert between python floats and other types when working with different data sources. Let me show you the main ones:

# String to float (from CSV files)
cpu_string = "23.7"
cpu_float = float(cpu_string)

# Float to string (for reports)
cpu_value = 23.7
cpu_display = str(cpu_value)

# Float to integer (for counts)
utilisation = 67.8
utilisation_whole = int(utilisation)  # Gets 67

Converting from float to integer chops off the decimal part. Doesn’t round, just removes everything after the decimal point. If you want proper rounding, use round() first.

This comes up constantly when you’re parsing different data sources. CSV files give you strings, SNMP gives you floats, some APIs give you integers. Need to know how to convert between them without losing data.

Had this exact problem last month actually. Pulling data from three different monitoring systems, each giving me different data types. Without proper conversion, half my calculations were wrong. Once I sorted the type conversions, everything worked perfectly.

Real Network Examples

Let me show you actual scenarios where python floats handling matters. These are proper examples from real work, not made-up rubbish.

Interface utilisation monitoring. You’ve got interface speeds and current usage, need to calculate percentage utilisation.

interfaces = {
    "GigabitEthernet0/1": {"speed": 1000.0, "current": 234.5},
    "GigabitEthernet0/2": {"speed": 1000.0, "current": 567.8},
    "TenGigabitEthernet0/1": {"speed": 10000.0, "current": 2345.6}
}

for interface, stats in interfaces.items():
    utilisation = (stats["current"] / stats["speed"]) * 100
    if utilisation > 80.0:
        print(f"High utilisation on {interface}: {utilisation:.1f}%")

Much more accurate than trying to track utilisation manually. That .1f bit formats it to one decimal place, so you get “23.7%” instead of “23.7234567%”.

Temperature monitoring across multiple devices:

device_temps = {
    "SW1-ACCESS": 42.7,
    "SW2-ACCESS": 45.2,
    "R1-EDGE-RTR": 48.9,
    "R2-CORE-RTR": 51.3
}

temp_threshold = 50.0

for device, temperature in device_temps.items():
    if temperature > temp_threshold:
        print(f"Temperature warning on {device}: {temperature}°C")
        send_snmp_trap(device, "HIGH_TEMP", temperature)

Automatically flags devices running too hot and sends SNMP traps to your monitoring system. Saved me loads of time compared to manually checking temperatures.

Response time analysis for network performance monitoring:

ping_results = [1.234, 1.567, 2.123, 1.890, 1.456]  # milliseconds

average_latency = sum(ping_results) / len(ping_results)
max_latency = max(ping_results)
min_latency = min(ping_results)

print(f"Average latency: {average_latency:.3f}ms")
print(f"Latency range: {min_latency:.3f}ms - {max_latency:.3f}ms")

if average_latency > 2.0:
    print("Network performance degraded")

The decimal precision matters for network latency measurements. Difference between 1.2ms and 1.9ms latency is significant for network performance.

Had a project last year where we needed to analyse WAN performance across multiple sites. Latency measurements were crucial for identifying which links were degrading. Without proper float handling, we’d have lost all the precision needed to spot performance trends. Boss was dead impressed when I could show exactly which links were having problems before users noticed.

Actually, that reminds me of another time. Had this customer complaining about slow network performance, but couldn’t pinpoint the problem. Used Python to analyse response times across all the network segments. Turned out one link had average latency of 1.8ms instead of the usual 1.2ms. Doesn’t sound like much, but when you’re doing thousands of transactions, that extra 0.6ms per transaction adds up. Found a dodgy cable that was causing packet retransmissions.

Python Floats Formatting for Reports

When you’re generating monitoring reports, you need to format floats properly for readability. Let me show you how:

cpu_usage = 23.7234
memory_usage = 67.890123
bandwidth_util = 45.0

# Clean formatting for reports
print(f"CPU: {cpu_usage:.1f}%")           # CPU: 23.7%
print(f"Memory: {memory_usage:.1f}%")     # Memory: 67.9%
print(f"Bandwidth: {bandwidth_util:.0f}%") # Bandwidth: 45%

Different format codes give you different presentations. :.1f gives one decimal place, :.2f gives two decimal places, :.0f rounds to whole numbers, :.3f gives three decimal places for precise measurements.

Had a project where we needed to generate daily network reports. CPU usage, interface utilisation, temperature readings, all formatted consistently. The decimal formatting made the reports much more readable than having random precision everywhere.

Thing is, if you don’t format properly, your reports look unprofessional. Management gets confused by seeing “23.7234%” next to “45%” for different devices. Consistent formatting makes everything look cleaner and more trustworthy.

Actually, learned this the hard way. First report I generated had numbers like “67.890123%” scattered throughout. Boss took one look and said it looked like I didn’t know what I was doing. Spent the weekend learning proper formatting, and the next report looked much better.

Scientific Notation in Network Calculations

Large network numbers often need scientific notation to keep them manageable. Let me show you:

# Interface speeds
gigabit_speed = 1e9      # 1,000,000,000 bits/second
ten_gig_speed = 1e10     # 10,000,000,000 bits/second

# Packet rates
packets_per_second = 2.5e6  # 2,500,000 packets/second

# Bandwidth calculations
total_throughput = 3.7e8    # 370 million bits/second

Scientific notation keeps the numbers manageable in your code while still representing the actual values accurately. Much easier to read 1e9 than counting nine zeros.

# Convert for display
print(f"Speed: {gigabit_speed:,.0f} bps")  # Speed: 1,000,000,000 bps
print(f"Rate: {packets_per_second:,.0f} pps")  # Rate: 2,500,000 pps

That :,.0f format adds commas as thousands separators and rounds to whole numbers. Makes the output much more readable.

Terminal output showing network monitoring results with python floats including properly formatted scientific notation and decimal values

Actually, scientific notation saved me loads of time on a recent project. Working with 100-gigabit interfaces, so all the calculations involved numbers with loads of zeros. Without scientific notation, my code would have been full of mistakes from miscounting zeros. With 1e11 instead of 100000000000, much less likely to make errors.

Precision Considerations for Network Monitoring

When working with network measurements, you need to understand float precision limitations. Let me walk through this:

# Bandwidth calculation that might have precision issues
bandwidth_1 = 123.456789
bandwidth_2 = 234.567890
total_bandwidth = bandwidth_1 + bandwidth_2

# Round to sensible precision for network measurements
total_rounded = round(total_bandwidth, 2)
print(f"Total bandwidth: {total_rounded} Mbps")

For network monitoring, two or three decimal places is usually sufficient precision. More than that becomes meaningless noise because your monitoring equipment doesn’t have that level of accuracy anyway.

But be aware of floating-point arithmetic quirks:

# This might surprise you
result = 0.1 + 0.2
print(result)  # Might show 0.30000000000000004

# For exact decimal arithmetic, use rounding
result = round(0.1 + 0.2, 1)
print(result)  # Shows 0.3

This rarely matters in practice for network monitoring because you’re usually working with thresholds rather than exact values. But worth knowing about if you’re doing complex calculations.

Had this bite me once when I was doing precise QoS calculations. Needed exact percentages for bandwidth allocation, but floating-point arithmetic was giving me tiny errors. Took ages to work out why my percentages didn’t add up to exactly 100%. Adding proper rounding sorted it.

Handling Invalid Measurements

Network monitoring produces invalid data constantly. Devices go offline, sensors fail, connections timeout. Your scripts need to handle this gracefully.

Let me show you a proper approach:

def process_cpu_reading(raw_value):
    try:
        cpu_float = float(raw_value)
        if 0.0 <= cpu_float <= 100.0:  # Valid CPU percentage range
            return cpu_float
        else:
            print(f"CPU reading out of range: {cpu_float}")
            return None
    except ValueError:
        print(f"Invalid CPU data: {raw_value}")
        return None

# Usage
cpu_values = ["23.7", "invalid", "150.0", "45.2"]
for value in cpu_values:
    cpu = process_cpu_reading(value)
    if cpu is not None:
        print(f"Valid CPU reading: {cpu}%")

This kind of validation prevents your monitoring scripts from crashing when they encounter bad data, which happens more often than you’d think.

SNMP timeouts, device reboots, sensor failures – all produce invalid readings that’ll break your scripts if you don’t handle them. Learned this the hard way during a network outage. Half the devices were offline, so my monitoring script was getting loads of invalid data. Without proper error handling, the script kept crashing just when I needed it most.

Actually, let me tell you the full story. This was about eighteen months back, right? Had this major outage, power supply failure took out half the network. My monitoring script was supposed to help identify which devices were still working, but it kept crashing every time it hit an offline device. Spent precious time during the outage fixing the script instead of fixing the network. Ever since then, I always include proper error handling.

PCEP Requirements for Floats

The PCEP exam covers specific aspects of python floats that you need to understand properly. Let me go through the main ones:

Floating-point literals – that’s just creating float variables:

temperature = 45.2      # Basic float literal
scientific = 1.5e3      # Scientific notation (1500.0)
negative = -23.7        # Negative float

Scientific notation using e or E:

big_number = 1.5e9      # 1,500,000,000
small_number = 2.3e-4   # 0.00023
bandwidth = 1E6         # 1,000,000 (E works same as e)

Float precision and accuracy issues:

# IEEE 754 double precision limits
precise_calc = 0.1 + 0.1 + 0.1  # Might not equal 0.3 exactly
print(f"Result: {precise_calc}")

# Use rounding for display
display_value = round(precise_calc, 1)
print(f"Rounded: {display_value}")

Type conversion between float and other types:

# String to float
user_input = "23.7"
threshold = float(user_input)

# Float to int (truncates decimal)
cpu_percent = 67.8
cpu_whole = int(cpu_percent)  # Gets 67

# Float to string
report_value = str(23.7)

These are the specific PCEP requirements, but understanding them through networking examples makes much more sense than generic mathematical examples.

Actually, let me mention something about the PCEP exam. They love testing edge cases with float precision. Might ask you what happens when you add 0.1 + 0.2, or how scientific notation works with negative exponents. The networking examples help you understand the concepts, but make sure you know the pure Python behaviour too.

Thing is, PCEP is about Python fundamentals, not networking specifically. But once you understand floats through networking examples, the abstract PCEP questions become much easier to answer.

Why This All Actually Matters

Understanding python floats properly is fundamental to any network monitoring or analysis you’ll do. CPU monitoring, bandwidth analysis, performance metrics – they all depend on handling decimal measurements correctly.

Get floats wrong and your monitoring thresholds won’t work properly. Alert levels will be wrong, capacity calculations will be inaccurate, performance analysis will give misleading results. Get them right and you can build reliable alerting and reporting systems that actually help manage your network.

The key thing is using floats for actual network measurements. CPU percentages, response times, bandwidth utilisation, temperature readings, power consumption levels. Not abstract mathematical problems that don’t help anyone.

When you’re working with monitoring systems, performance analysis, capacity planning, all the calculations become much easier once you’re comfortable with float operations and formatting. You can focus on the networking problems instead of wrestling with data type issues.

Python’s float handling is robust enough that you don’t need to worry about most of the mathematical complexities. Just understand when to use floats versus integers, how to format them for reports, and how to handle invalid data gracefully.

Actually, let me tell you something that really drove this home for me. Had a conversation with a colleague who’d been struggling with Python for months. Kept getting frustrated because his monitoring scripts weren’t working properly. Turns out he was storing everything as strings and wondering why his calculations were wrong. Spent an hour showing him proper float handling, and suddenly everything clicked. His scripts started working, alerts became accurate, reports looked professional.

That’s the difference proper understanding makes. It’s not just about passing PCEP or looking clever. It’s about writing scripts that actually work reliably in real network environments.

That’s floats sorted properly. You understand what they are, how they work with network monitoring data, common mistakes to avoid, and practical applications for real network engineering tasks. Much more useful than learning about theoretical mortgage calculations that have nothing to do with your actual job.


External Link: Python Float Documentation – official Python documentation for floating-point operations and precision

1 thought on “Python for Network Engineers Blog 10: Python Floats”

  1. Pingback: Python for Network Engineers Blog 11: Python Booleans - RichardKilleen

Leave a Reply

Your email address will not be published. Required fields are marked *