Programming for Computations – Python 2nd Edition

Author: Svein Linge, Hans Petter Langtangen
File Type: pdf
Size: 7.1 MB
Language: English
Pages: 350

Programming for Computations – Python 2nd Edition: A Practical Guide for Engineering, Science, and Technical Computing

Introduction

Engineering and scientific work increasingly depends on computation. Whether an engineer is processing experimental measurements, analysing structural data, modelling a physical system, automating repetitive calculations, or visualising results, programming can turn a slow manual workflow into a fast and repeatable process.

Python is particularly attractive for computational work because it combines a relatively simple syntax with a large ecosystem of scientific, engineering, mathematical, and data-processing libraries. A beginner can write a useful program with only a few lines, while an experienced professional can build sophisticated computational workflows around the same language. 🐍⚙️

Programming for computations is therefore not simply about learning Python syntax. It is about learning how to translate a technical problem into a logical sequence of computational operations.

Image

For students, computational programming provides a bridge between mathematical theory and practical engineering. For professionals, it can improve productivity, reproducibility, automation, and decision-making.

This article explores how Python can be used for computational problems, beginning with fundamental concepts and progressing toward professional engineering applications.


Background Theory

From Manual Computation to Computational Thinking

Traditional engineering education often introduces formulas, tables, calculators, spreadsheets, and specialised software. These tools remain valuable, but programming introduces another level of flexibility.

Instead of repeatedly performing the same operation manually, an engineer can describe the procedure once and allow a computer to execute it thousands or millions of times.

The general computational workflow can be represented as:

Problem → Inputs → Processing → Results → Validation → Decision

Python fits naturally into this workflow.

Why Python Is Suitable for Computations

Python has several characteristics that make it useful in engineering and scientific environments:

  • Clear and readable syntax
  • Large scientific-computing ecosystem
  • Support for numerical arrays
  • Data-analysis capabilities
  • Visualisation libraries
  • File-processing tools
  • Automation capabilities
  • Integration with databases and external software
  • Support for object-oriented and procedural programming
  • Cross-platform compatibility

Libraries such as NumPy, SciPy, pandas, and Matplotlib extend Python from a general-purpose programming language into a powerful computational environment.

Computational Thinking

A strong computational solution normally involves four major ideas:

Decomposition: Break a complicated engineering problem into smaller tasks.

Abstraction: Focus on the information and operations that actually matter.

Automation: Make the computer perform repetitive operations.

Validation: Check whether the computational output makes physical and engineering sense.

This final step is particularly important. A program can execute perfectly and still produce an incorrect engineering result if the assumptions, units, or input data are wrong.


Definition

What Is Programming for Computations?

Programming for computations is the practice of using a programming language to formulate, automate, analyse, and solve numerical, scientific, mathematical, and engineering problems.

In Python, this commonly involves:

  • Variables for storing values
  • Operators for processing information
  • Conditional statements for decision-making
  • Loops for repetition
  • Functions for reusable operations
  • Lists and arrays for collections of values
  • Libraries for specialised computation
  • Files for persistent data
  • Visualisation tools for interpreting results

The objective is not merely to produce code. The objective is to create a reliable computational procedure.

Python as a Computational Tool

A simple Python program can receive engineering data, process it, and generate useful output.

For example, an engineer might create a program that:

  1. Reads measurements from a file.
  2. Checks the incoming data.
  3. Removes invalid records.
  4. Processes the measurements.
  5. Generates statistical information.
  6. Produces a graph.
  7. Saves a report.

That workflow could potentially replace hours of repetitive manual work. 🚀


Step-by-Step Explanation: Building a Computational Python Workflow

Step 1: Define the Engineering Problem

Before writing Python code, clearly identify what needs to be solved.

Ask:

  • What information is available?
  • What information is required?
  • What assumptions are being made?
  • What constraints exist?
  • What should the final output look like?

A vague problem usually produces complicated code. A clearly defined problem produces a more manageable computational workflow.

Step 2: Identify Inputs and Outputs

Separate the information entering the program from the information produced by it.

For example, a laboratory analysis program might accept:

  • Sensor readings
  • Time information
  • Material properties
  • Environmental conditions

The output might contain:

  • Processed measurements
  • Statistical summaries
  • Graphs
  • Warning messages
  • A final engineering report

Step 3: Divide the Problem into Tasks

Avoid writing one enormous program.

Instead, divide the workflow into logical components such as:

Data input → Validation → Processing → Analysis → Visualisation → Export

This makes debugging and maintenance considerably easier.

Step 4: Implement the Basic Python Logic

Python provides fundamental programming structures that support computational workflows.

A variable can store information. A conditional statement can determine what happens under different circumstances. A loop can repeat an operation. A function can package a frequently used procedure.

For example, instead of manually checking hundreds of measurements, a Python program can inspect each value and automatically identify records that violate predefined criteria.

Step 5: Use Appropriate Libraries

Python becomes especially powerful when combined with specialised libraries.

NumPy is widely used for numerical arrays and mathematical operations.

pandas is useful for tabular data and data cleaning.

Matplotlib can create engineering plots and scientific visualisations.

SciPy provides tools for optimisation, interpolation, numerical integration, statistics, and scientific computing.

SymPy can be useful for symbolic mathematics.

Image

Image

Image

Image

Step 6: Validate the Results

Never assume that successful program execution means the engineering analysis is correct.

Compare results against:

  • Known reference values
  • Hand calculations
  • Experimental observations
  • Expected physical behaviour
  • Independent software
  • Boundary conditions

Step 7: Document the Workflow

Professional computational programs should explain what they do.

Useful documentation includes:

  • Comments
  • Function descriptions
  • Input requirements
  • Units
  • Assumptions
  • Expected outputs
  • Version information

Good documentation makes a computational tool easier for another engineer to understand and trust.


Comparison: Python vs Traditional Computational Approaches

FeatureManual CalculationSpreadsheetPython
Repetitive calculationsSlowGoodExcellent
Large datasetsDifficultModerateExcellent
AutomationVery limitedModerateExcellent
VisualisationLimitedGoodExcellent
ReproducibilityLowModerateHigh
Custom algorithmsDifficultModerateExcellent
Learning curveLow initiallyLow–moderateModerate
Integration with softwareLimitedModerateExcellent
Version controlPoorLimitedExcellent

Python vs Spreadsheets

Spreadsheets remain useful for quick calculations, small datasets, and interactive exploration.

Python becomes increasingly advantageous when workflows involve large datasets, repeated calculations, complex algorithms, automated reports, or integration with other systems.

The best choice is not always Python instead of spreadsheets. In many professional environments, Python and spreadsheets work effectively together.


Diagrams and Computational Architecture

Basic Computational Architecture

A typical engineering Python application can be visualised as:

┌──────────────────┐
│ Engineering Data │
└────────┬─────────┘
         ↓
┌──────────────────┐
│ Data Validation  │
└────────┬─────────┘
         ↓
┌──────────────────┐
│ Python Processing│
└────────┬─────────┘
         ↓
┌──────────────────┐
│ Numerical Analysis│
└────────┬─────────┘
         ↓
┌──────────────────┐
│ Visualisation    │
└────────┬─────────┘
         ↓
┌──────────────────┐
│ Engineering Report│
└──────────────────┘

Computational Components

ComponentPurposeExample
InputReceive informationCSV measurement file
ValidationDetect problematic dataMissing values
ProcessingTransform informationData filtering
AnalysisExtract useful resultsStatistical analysis
VisualisationCommunicate findingsEngineering plots
ExportSave resultsCSV or PDF report

When to Add Visualisation

Graphs can reveal patterns that numerical output alone may hide.

For example, plotting sensor measurements against time can expose:

  • Sudden spikes
  • Long-term trends
  • Missing intervals
  • Abnormal readings
  • Cyclic behaviour

Visualisation is therefore not merely decorative. It can become part of the engineering validation process. 📊


Practical Examples

Example 1: Processing Temperature Measurements

Imagine a manufacturing facility collecting temperature measurements every few seconds.

A Python program could:

  1. Import the measurement file.
  2. Identify missing records.
  3. Detect unusual values.
  4. Group measurements by time period.
  5. Calculate summary statistics.
  6. Generate a temperature trend graph.
  7. Save the processed information.

Instead of manually inspecting thousands of records, the engineer receives an organised analysis.

Example 2: Structural Engineering Data

A structural engineer could use Python to process information collected from sensors installed on a structure.

The program could organise measurements, identify unusual changes, compare different monitoring periods, and generate visual reports.

Python does not replace engineering judgement. Instead, it helps the engineer process information efficiently.

Example 3: Manufacturing Quality Control

A manufacturing company may collect dimensions from thousands of components.

Python can automatically analyse the measurements and classify records according to predefined quality criteria.

The result can be a report showing production trends, abnormal measurements, and potential quality issues.


Real-World Applications

Civil and Structural Engineering

Python can assist with:

  • Structural data processing
  • Survey-data analysis
  • Construction monitoring
  • Material testing
  • Geotechnical data processing
  • Building-performance analysis
  • Automated engineering reports

Mechanical Engineering

Mechanical engineers can use Python for:

  • Experimental data analysis
  • Machine monitoring
  • Thermal-system analysis
  • Design optimisation
  • Performance testing
  • Automation

Electrical Engineering

Applications include:

  • Signal processing
  • Sensor analysis
  • Power-system data
  • Circuit-data processing
  • Control-system development
  • Automated testing

Aerospace Engineering

Python is frequently useful for:

  • Flight-data analysis
  • Simulation workflows
  • Optimisation
  • Experimental research
  • System modelling
  • Visualisation

Data Science and Research

Researchers can use Python to combine numerical computation, statistical analysis, machine learning, visualisation, and automated data processing in a single workflow.


Common Mistakes

Writing Code Before Understanding the Problem

One of the most frequent beginner mistakes is immediately opening an editor and writing code.

Solution: Define the inputs, outputs, assumptions, and workflow first.

Ignoring Units

A computational program may process numbers correctly while the engineer has supplied inconsistent units.

Solution: Store units explicitly in documentation and convert input data to a consistent system.

Creating Huge Scripts

Large scripts become difficult to test and maintain.

Solution: Divide the program into functions and logical modules.

Trusting Results Without Validation

A Python program can produce a convincing graph containing incorrect results.

Solution: Compare computational results with independent checks.

Using Libraries Without Understanding Them

Libraries save time, but blindly applying functions can create misunderstandings.

Solution: Learn what the function expects, what it returns, and what assumptions it makes.


Challenges and Solutions

ChallengeEffectPractical Solution
Large datasetsSlow processingUse efficient arrays and data structures
Poor-quality dataIncorrect conclusionsBuild validation procedures
Complex programsDifficult maintenanceUse functions and modules
Numerical instabilityUnreliable resultsValidate methods and test edge cases
ReproducibilityDifficult verificationRecord inputs and software versions
Lack of documentationKnowledge lossDocument assumptions and workflows

Performance Challenges

Python is highly capable, but computational performance can become important for extremely large workloads.

A sensible strategy is to first create a correct and readable solution. Optimisation should then target the parts of the workflow that actually consume significant resources.


Case Study: Automating Laboratory Data Analysis

The Initial Problem

Consider an engineering laboratory that performs repeated material tests.

Technicians collect measurements and manually transfer them into spreadsheets. After every testing session, someone cleans the data, generates graphs, calculates summaries, and prepares a report.

This workflow introduces opportunities for:

  • Data-entry errors
  • Inconsistent formatting
  • Repeated manual work
  • Delayed reporting
  • Inconsistent analysis procedures

The Python Solution

A Python-based workflow can automatically import the measurement files and perform a standard sequence of operations.

The program validates the records, organises the measurements, identifies suspicious values, generates plots, and produces structured output.

The Engineering Benefit

The greatest advantage is not simply speed.

A well-designed workflow creates consistency.

Every test follows the same computational procedure, making comparisons easier and reducing repetitive manual operations.

Lessons Learned

The case demonstrates an important principle:

Automation should standardise a well-understood engineering process, not hide a poorly understood one.

The engineer remains responsible for selecting appropriate assumptions, interpreting results, and deciding whether the output is technically reasonable.


Essential Tips for Students and Professionals

Start Small 🐍

Do not attempt to build a complete engineering application during your first programming project.

Start with a small task such as reading a dataset, filtering information, or generating a graph.

Learn Python Through Engineering Problems

Instead of learning programming entirely through abstract exercises, apply concepts to realistic technical problems.

For example:

  • Learn loops by processing measurements.
  • Learn functions by creating reusable engineering calculations.
  • Learn arrays by processing sensor data.
  • Learn plotting by visualising experimental results.

Build a Reusable Toolkit

Professionals can gradually create reusable functions for:

  • Data cleaning
  • Unit conversion
  • Plot generation
  • Report creation
  • File processing
  • Validation

Over time, these tools can become a personal computational engineering toolkit. 🛠️

Use Version Control

For professional projects, version control helps track changes to computational code and improves collaboration.

Test Before Trusting

Create test cases with known expected results before using a program for important engineering work.

Keep Humans in the Loop

Automation is powerful, but engineering decisions should remain subject to professional judgement, verification, and appropriate standards.


Frequently Asked Questions

Is Python difficult for engineering students?

Python is generally approachable for beginners because its syntax is relatively readable. The bigger challenge is learning how to translate an engineering problem into a logical computational workflow.

Can Python replace engineering software?

Usually, Python should be viewed as a complementary tool rather than a universal replacement. It can automate calculations, process data, create models, and connect different tools, while specialised engineering software may remain essential for particular tasks.

Which Python libraries should engineers learn first?

A practical starting point is NumPy for numerical computing, pandas for tabular data, and Matplotlib for visualisation. SciPy can then extend capabilities into more advanced scientific computing.

Is Python useful for civil engineering?

Yes. It can support structural-data processing, surveying workflows, material testing, construction data analysis, monitoring systems, optimisation, and report automation.

Should beginners learn mathematics before Python?

Basic mathematical understanding is valuable, particularly for engineering applications, but beginners do not need to master advanced mathematics before learning Python. Programming and mathematics can be learned together.

Can Python handle large engineering datasets?

Yes. Python has a strong ecosystem for data processing. For very large datasets, performance and memory considerations become important, and engineers may need specialised data-processing techniques.

How can Python improve engineering productivity?

Python can automate repetitive calculations, process large numbers of files, generate reports, analyse measurements, create visualisations, and connect different stages of an engineering workflow.

Is programming knowledge useful for professional engineers?

Absolutely. Programming can become a valuable engineering skill because modern technical work increasingly involves simulation, automation, data analysis, optimisation, monitoring, and digital workflows.


Conclusion

Programming for computations with Python provides engineers and scientists with a flexible way to transform technical problems into repeatable computational workflows. 🐍⚙️📊

The real value of Python is not simply that it can perform calculations quickly. Its strength comes from combining computation, automation, data analysis, visualisation, and reproducibility within one environment.

For beginners, the best approach is to learn fundamental Python concepts and immediately apply them to practical technical problems. For experienced professionals, Python can evolve into a powerful automation and analysis platform capable of connecting datasets, simulations, experiments, and reporting processes.

The most effective computational engineer is not necessarily the person who writes the most complicated code. It is the person who can take a real-world engineering problem, understand its assumptions and limitations, design a clear computational workflow, validate the results, and communicate those results effectively.

As engineering becomes increasingly data-driven, the ability to think computationally and program effectively is becoming an important professional advantage across the USA, UK, Canada, Australia, and Europe. 🚀

Python + Engineering Knowledge + Validation + Automation = A Powerful Computational Workflow.

Unlock exclusive content
Enjoy all premium content by watching a short ad
Preparing ad...
BY ADX360