Doing Math with Python: Use Programming to Explore Algebra, Statistics, Calculus, and More - podcast episode cover

Doing Math with Python: Use Programming to Explore Algebra, Statistics, Calculus, and More

May 08, 202617 min
--:--
--:--
Download Metacast podcast app
Listen to this episode in Metacast mobile app
Don't just listen to podcasts. Learn from them with transcripts, summaries, and chapters for every episode. Skim, search, and bookmark insights. Learn more

Episode description

Explores the intersection of programming, mathematics, and science. The author demonstrates how to use Python 3 to solve high school-level problems in fields such as algebra, statistics, calculus, and geometry. Readers learn to build practical tools like multiplication table generators, unit converters, and quadratic equation solvers while mastering core coding concepts. Beyond simple calculations, the text introduces specialized libraries like SymPy for symbolic math and matplotlib for data visualization and fractal generation. Saha emphasizes a hands-on approach, using interactive coding challenges to help students and teachers automate tedious calculations and simulate complex real-world events. Overall, the source serves as a comprehensive guide for using software to make mathematical exploration more engaging and efficient.

You can listen and download our episodes for free on more than 10 different platforms:
https://linktr.ee/cyber_security_summary

Get the Book now from Amazon:
https://www.amazon.com/Doing-Math-Python-Programming-Statistics-ebook/dp/B014EELUFQ?&linkCode=ll2&tag=cvthunderx-20&linkId=017a991011ee62ba220e7412ed01f005&language=en_US&ref_=as_li_ss_tl

Discover our free courses in tech and cybersecurity, Start learning today:
https://linktr.ee/cybercode_academy

Transcript

Speaker 1

So I want you to think back to high school math for a second. Oh boy, right, just picture it. You're sitting at this tiny, uncomfortable desk. You've got a yellow number two pencil in your hand, and you're just staring down at this massive page of complex equations, endless rows of them, exactly, and the expectation was that you'd solve them all completely by hand, just grinding through the arithmetics step by tedious step.

Speaker 2

Yeah, which is I mean, it's the equivalent of being asked to dig the foundation for a brand new house, but the only tool you're given is a teaspoon.

Speaker 1

A teaspoon.

Speaker 2

Yeah. You spend so much energy on the sheer physical labor of moving the dirt that you completely lose sight of the architectural principles behind the house you're trying to build.

Speaker 1

The labor just completely distracts you from the actual architecture. And well, that is exactly why A Met SAHA's book Doing Math with Python is such a crucial stack of source material for us today.

Speaker 2

It really is.

Speaker 1

We're looking at how coding acts as the ultimate shark to mathematical fluency. The mission of this deep dive is to see what happens when you put down that teaspoon and bring in a bulldozer instead.

Speaker 2

I love that analogy.

Speaker 1

Right, You outsource the arithmetic to this eager digital assistant, which frees up your cognitive load to build complex simulations and uncover hidden patterns.

Speaker 2

It represents a fundamental paradigm shift in how we approach numbers. You transition from being a biological calculator, which, let's be honest, humans are frankly terrible.

Speaker 1

Are we really are? We make so many tiny mistakes exactly.

Speaker 2

You go from that to being a mathematical director. You're orchestrating the logic while the machine handles the brute force.

Speaker 1

But to wield that bulldozer, you know, you have to learn how to speak the machine's language first. And Python for all its flexibility, well, it requires strict mathematical hygiene.

Speaker 2

Yeah, very strict.

Speaker 1

We aren't just talking about basic arithmetic order of operations here like pemdas. We are talking about how the language fundamentally categorizes data, right.

Speaker 2

Because to a human mind, and the number three is just it's just the concept of three. Sure, whether it's written as a single digit or three point zero, or as a fraction like three over one. Our brains process it is the exact same mathematical value, but Python allocates memory and operations differently depending on this specific type of data.

Speaker 1

Python distinguishes really strictly between an integer, which is an inlet like three, and a floating point number, so a float like three point.

Speaker 2

Zero, right.

Speaker 1

And I think a lot of people initially view this as Python just being pedantic. You write a script, you expect a whole number, a user inputs a decimal, and the whole program just.

Speaker 2

Crashes, It just halts.

Speaker 1

It feels like you are dealing with a highly skilled but entirely literal minded chef. Like if a recipe calls for a whole egg and integer and you hand them a scrambled egg afloat, they won't know what to do and they'll just throw a fit.

Speaker 2

That's a great way to put it, And that fit Python throws is what we call an exception, right and exception. What's fascinating here is that this strict type casting is actually a brilliant enforcer of mathematical rigor. Python gets even more granular than just integers and floats. Actually, oh really, like how well you can work with explicit fractions using the format fraction three four, and it even handles complex numbers natively.

Speaker 1

Wait, complex numbers like with imaginary parts.

Speaker 2

Yeah, it uses J instead of I, so you'll see outputs like two plus three J right there in the console.

Speaker 1

Wow, which is an incredible powerful feature for you know, engineering and physics applications.

Speaker 2

Absolutely, But the.

Speaker 1

Friction always happens at the point of user input, doesn't it. When you ask a user to type a variable into your program, Python reads that input as a string of text by.

Speaker 2

Default, right, It sees the character three fight not the mathematical value.

Speaker 1

Of three, So the programmer has to explicitly convert that text string into the correct mathematical type.

Speaker 2

And if you mismanage that conversion, you trigger one of those exceptions. I mean, if the user inputs a fraction string like thirty four and your code blindly tries to cast that directly into an integer, Python raises value.

Speaker 1

Air it just panics exactly.

Speaker 2

Or if you're annoying formula inadvertently allows a zero to slip into the denominator of a calculation, you trigger a zero division error.

Speaker 1

I want to look closely at how the source material handles this, because using these try accept blocks in Python to manage these errors. It isn't just a band aid for bad user.

Speaker 2

Input, No, not at all.

Speaker 1

It forces you to rigorously define the mathematical parameters of your environment. You're actively building the domain restrictions of your function.

Speaker 2

That is the perfect way to frame it. Anticipating a zero division error means you have to deeply understand the assymp totes right, and the undefined behavior of the formula you're modeling.

Speaker 1

You have to know where the math breaks.

Speaker 2

Yes, you have to teach the computer how to handle mathematical impossibilities gracefully. Working through those exceptions builds a structural understanding of mathematical rules that is just It's far deeper than just skipping over a tricky problem on a paper worksheet.

Speaker 1

So once we've established these strict guard rails and define mathematical domains, the real power of the language unlocks. We move from executing single isolated commands to automating the.

Speaker 2

Tedium because why do the same thing twice?

Speaker 1

Right. Once you can communicate the logic of a calculation to Python perfectly, there is absolutely no reason to ever do that calculation by hand again.

Speaker 2

And this is where we start utilizing loops by pairing a four loop with a range function, you shift your focus from finite problem solving to infinite generation.

Speaker 1

So instead of calculating a single multiplication problem, you just instruct Python to generate endless multiplication tables in like a fraction of a.

Speaker 2

Second, exactly, you can write a loop that calculates all the factors of a massive multi digit integer almost instantly.

Speaker 1

Think about the application for unit conversion two. The text uses the example of comparing a temperature of eighty six degrees fahrenheit against three zho three point one five kelvin.

Speaker 2

Which is mathematically impossible to analyze in its raw state.

Speaker 1

Right, it's apples and oranges.

Speaker 2

Yeah, I have to mathematically standardize the space before any logical comparison can occur. Soe.

Speaker 1

You write a quick Python script that asks the user for the value, applies the appropriate conversion formula, and spits out the standardized result.

Speaker 2

It does the heavy lifting for you.

Speaker 1

But okay, let's unpack this. The source material spends significant time detailing how to program the quadratic formula. We're talking about finding the roots for the classic algebra equation x squared plus b x plus c equals zero.

Speaker 2

Right, A staple of high school math.

Speaker 1

Yeah, and it breaks down the process systematically, first calculating the discriminate ah.

Speaker 2

The D equals B squared minus four x.

Speaker 1

Part yes, that portion of the formula, and then using that isolated value to find the two roots.

Speaker 2

And it leverages that native complex number support we mentioned earlier too.

Speaker 1

Right, Like if you enter one one in one for the A, B, and C variables, Python doesn't panic because the discriminant is negative.

Speaker 2

No, it just calmly outputs complex roots like negative point five plus point eight sixt six. J.

Speaker 1

It's so cool, But uh, I have to play the devil's advocate for a second here. Sure, go for it if you're a student, isn't writing a quadratic equation solver just a highly engineered way to cheat at your homework? I mean, you plug in the variables, the machine gives you the answer, and you learn nothing about the actual math.

Speaker 2

Well, if we connect this to the bigger picture, writing this solver algorithm requires a significantly higher level of mathematical mastery than just executing the formula.

Speaker 1

On paper, because you are building the architecture, not just turning the crank.

Speaker 2

Precisely when you solve a single quadratic equation on paper, you're just plugging numbers into a pre existing machine. But by programming the quadratic formula, you aren't solving a single equation.

Speaker 1

You're solving all of them.

Speaker 2

Yes, you are teaching a machine how to solve every quadratic equation in existence. You have to break the formula down into his constituent logical components, define the variables, handle the discriminate operation separately, and.

Speaker 1

Account for those complex route pathways if the number goes negative exactly.

Speaker 2

That requires a level of algorithmic master read that goes far beyond just plugging numbers into a test.

Speaker 1

You're stepping out of the role of the calculator and into the role of the mathematician. You really are, but you know, building an algorithmic engine that can spit out thousands of complex roots or endless multiplication tables, it introduces a.

Speaker 2

New problem, beta overload.

Speaker 1

Staring at a terminal window scrolling with thousands of calculated integers is completely useless to the human brain. To actually understand data at that scale, we have to stop reading numbers and start looking at shapes.

Speaker 2

Which brings us to data visualization. Specifically, the map plot lib package and Python and its pipe plot module.

Speaker 1

Yes, this is how we map those massive arrays of numbers onto a Cartesian coordinate plane.

Speaker 2

The source material uses a brilliant, highly relatable example to demonstrate this. Actually, it uses historical temperature data from Central Park in New York City.

Speaker 1

Oh right, the data set tracking the average annual temperatures between the years twenty twenty twelve.

Speaker 2

Yeah, and it's a relatively small data set, just thirteen data points, ranging from a low of fifty three point nine degrees to a high of fifty seven point three degrees fahrenheit.

Speaker 1

Now, if you just look at that data in a spreadsheet, it's just a block of text. It's totally static.

Speaker 2

Just numbers on a screen.

Speaker 1

But when you feed that array into matt plotlib, you map the years onto the x axis and the temperatures onto the y axis. The text even shows how you can layer the monthly temperature data for multiple specific years, say two thousand and twenty six and twenty twelve, all onto the exact same graph.

Speaker 2

Right. You assign different colors to each tear's line. You generate a legend so the viewer knows what they're looking at.

Speaker 1

You define the title and the axis labels.

Speaker 2

And suddenly the deity yields a narrative. You can visually identify these distinct sharp peaks occurring every July across all three years.

Speaker 1

It immediately transforms raw numbers into a clear story about seasonal variance and historical warming trends.

Speaker 2

It's incredibly satisfying to see.

Speaker 1

But here's where it gets really interesting, and the book highlights a major trap in data visualization that programmers fall into all the time.

Speaker 2

The scaling issue.

Speaker 1

Yes, when you feed that initial annual Central Park data into matplot lib and rely on the default settings, the resulting graph looks like a violent, dramatic roll and coaster of extreme temperature shifts.

Speaker 2

The visual spikes and drops appear massive, almost catastrophic.

Speaker 1

Really, but it's an optical illusion. The software automatically optimizes the visual variants by zooming the y axis in incredibly tightly around the data.

Speaker 2

Right, it tries to fill the space exactly.

Speaker 1

The bottom boundary of the graph defaults to fifty three point zero degrees and the top boundary is set just above fifty seven point five degrees. It takes a relatively narrow four degree band of variants and stretches it vertically to fill the entire visual field.

Speaker 2

This raises an important question about modern data literacy. Honestly, when media outlets or social media platforms publish charts, they frequently rely on or intentionally exploit these exact default scaling behaviors.

Speaker 1

Happens all the time.

Speaker 2

If you don't understand how a graph is constructed underneath the hood, you're entirely at the mercy of the person who generated it.

Speaker 1

They can manipulate the axis boundaries to make a minor statistical fluctuation look like an unprecedented crisis.

Speaker 2

Or conversely, they can flatten a massive change into a straight line by zooming out too far.

Speaker 1

So the defense mechanism here has to be taking manual control of those visual boundaries. Does the text use the axis function to just pin that y axis down to a baseline of zero.

Speaker 2

It does by explicitly coding the parameter i'men equal zero. The programmer overrides that default zoom.

Speaker 1

And the roller coaster immediately flattens out exactly.

Speaker 2

The dramatic, terrifying spikes are contextualized against absolute zero, and they become a gentle, much more realistic ripple at the very top of the graph.

Speaker 1

It proves that learning to code your own graphs is a vital active defense against being misled by manipulated statistics in the real world.

Speaker 2

You know how the trick is performed, so you can't be fooled by the.

Speaker 1

Prestige That is such a critical critical thinking skill. So we've successfully modeled static historical data, and we've learned to defend against statistical illusions. But the ultimate test of mathematical fluency is moving from static numbers to dynamic systems.

Speaker 2

Stepping out of statistics and into the physical laws of the universe.

Speaker 1

Yes, modeling physics using mathematical formulas in Python is where the language truly acts as a sandbox for reality. A foundational example from the text is plotting Newton's law of universe gravitation AH.

Speaker 2

The classic formula F equals G times M one times m two all divided by R squared right.

Speaker 1

It calculates the gravitational force between two bodies based on their masses and the distance between them, and the.

Speaker 2

Script provided in the book generates an array of distances iterating from one hundred meters all the way up to one thousand meters.

Speaker 1

When you plot that resulting gravitational force against those increasing distances. You don't just see a list of decreasing numbers. You visually prove the inverse proportional nonlinear relationship.

Speaker 2

The inverse square law.

Speaker 1

Yes, you get this perfect sweeping asymptotic curve on the graph that visually demonstrates how rapidly gravity weakens as the objects move apart.

Speaker 2

It's a nonlinear decay, and seeing the shape of that decay makes the physics intuitive in a way equations sometimes aren't.

Speaker 1

It completely bridges the gap between the algebraic formula and the physical reality it describes.

Speaker 2

But the absolute zenith of this modeling conceptually has to be the projectile motion simulation.

Speaker 1

Oh I love this part so much. This brings literally everything we've talked about algebra, trigonometry, loops, and visualization into one single script.

Speaker 2

It's the grand finale picture this.

Speaker 1

You throw a ball with an initial velocity of five meters per second, launched at exactly a forty five degree angle.

Speaker 2

Okay, so first you have to use trigonometry, the math dot cos and math dot sin functions to break that single velocity vector into its horizontal and vertical components.

Speaker 1

Right, because it's moving up and forward at the same time, wow, and applying the constant of graph pulling it down at an acceleration of nine point eight meters per second squared. The basic high school physics formula tells us the total flight.

Speaker 2

Time the ball will hit the ground in exactlyer point seven to two one five four seconds.

Speaker 1

But knowing the final destination isn't the goal here. We want to map the entire journey.

Speaker 2

We want to see the arc.

Speaker 1

So the script utilizes a wile loop to calculate the ball's exact X and y coordinates at microscopic intervals. Specifically, every zero point zero zero one seconds of that.

Speaker 2

Flight wow, every millisecond.

Speaker 1

Every millisecond, it calculates the horizontal distance traveled in that millisecond. It calculates the vertical drop caused by gravity in that millisecond, plots the dot and repeats.

Speaker 2

It runs that calculation hundreds of times until the vertical coordinate hits zero.

Speaker 1

It is essentially the exact underlying physics engine for a video game like Angry Birds.

Speaker 2

That's a perfect analogy.

Speaker 1

You are creating a digital sandbox where you map out exactly where a physical object exists in space millisecond by millisecond.

Speaker 2

What's fascinating. Here is how this loop bridges the continuous and the discrete. I mean, in physical reality, the ball's flight is a continuous, unbroken arc, but computers can only process discrete, quantified steps. By looping the calculation every point zero zero one seconds, you're essentially performing rudimentary numerical integration.

Speaker 1

You're slicing continuous time into tiny calculable slivers to approximate reality exactly.

Speaker 2

The smaller the time step, the closer your digital simulation gets to the true continuous curve of the physical world.

Speaker 1

It's just incredible. I mean, you are predicting the future path of an object through space and time using nothing but logic loops and high school math.

Speaker 2

It transforms mathematics with an abstract exercise on a chalkboard into a tangible mechanism for literally simulating reality. It's a superpower, it really is.

Speaker 1

Well, we have covered massive ground today, so let's synthesize the journey we just took through Amitsaha's work.

Speaker 2

Let's do it.

Speaker 1

We started by exploring Python's strict mathematical hygiene right learning how casting types and defining exceptions like value errors forces us to truly understand the boundaries and domains of our formulas.

Speaker 2

We used loops to automate algebraic algorithms, realizing that writing a quadratic solver is about architecting logic, not just finding a quick answer.

Speaker 1

We expose the visual illusions hidden inside default data visualizations, and finally, we sliced continuous time into discrete loops to literally simulate the physical laws of the universe.

Speaker 2

And for you listening, whether you're aggressively prepping for a highly technical engineering role or you're simply deeply curious about the architecture of the digital world, Adopting Python is a mathematical tool represents a massive paradigm.

Speaker 1

Shift that acts as a lever.

Speaker 2

Yes, it lifts the exhausting mechanical burden of calculation off your shoulders, allowing your intellect to focus entirely on raw innovation, pattern recognition, and complex problem solving.

Speaker 1

So what does this all mean? We started this deep dive talking about the sheer physical exhaustion of digging a foundation with a teaspoon. But if computers can now seamlessly handle all the grunt work of executing complex mathematical formulas and physics simulations.

Speaker 2

In a fraction of a second, no less right.

Speaker 1

In milliseconds, will the future of human mathematics look less and less like tedious calculation and more like pure philosophy and art, something for you to maul over next time you reach for that yellow number two pencil

Transcript source: Provided by creator in RSS feed: download file
For the best experience, listen in Metacast app for iOS or Android