0% found this document useful (0 votes)
74 views105 pages

Geometry For Programmers, MEAP Version 3 Oleksandr Kaleniuk PDF Download

Uploaded by

vjepxqt558
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views105 pages

Geometry For Programmers, MEAP Version 3 Oleksandr Kaleniuk PDF Download

Uploaded by

vjepxqt558
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 105

Geometry for Programmers, MEAP Version 3

Oleksandr Kaleniuk pdf download

https://ebookmeta.com/product/geometry-for-programmers-meap-version-3-oleksandr-kaleniuk/

★★★★★ 4.7/5.0 (24 reviews) ✓ 94 downloads ■ TOP RATED


"Great resource, downloaded instantly. Thank you!" - Lisa K.

DOWNLOAD EBOOK
Geometry for Programmers, MEAP Version 3 Oleksandr Kaleniuk
pdf download

TEXTBOOK EBOOK EBOOK META

Available Formats

■ PDF eBook Study Guide TextBook

EXCLUSIVE 2025 EDUCATIONAL COLLECTION - LIMITED TIME

INSTANT DOWNLOAD VIEW LIBRARY


Collection Highlights

Geometry for Programmers (MEAP v11) Oleksandr Kaleniuk

Geometry for Programmers MEAP V03 Oleksandr Kaleniuk

Geometry for Programmers Final Release 1st Edition


Oleksandr Kaleniuk

Watson the Countess 1 The Baskerville Curse 1st Edition


Anna Lord
Playing With Fire: Eagle's Nest Securities Book 2 Anna
Blakely

Convergence of Cloud with AI for Big Data Analytics:


Foundations and Innovation 1st Edition Danda B. Rawat

The Untold History of Japanese Game Developers Volume 3


John Szczepaniak

Understanding the Science and Practice of Public Health


1st Edition Crosby

High Stick Heartthrob (SOLA Empire Hockey #1) 1st Edition


London Casey
Legion Dragon Rules 1 1st Edition Tia Didmon
MEAP Edition
Manning Early Access Program
Geometry for Programmers
Version 3

Copyright 2022 Manning Publications

For more information on this and other Manning titles go to


manning.com

©Manning Publications Co. To comment go to liveBook


welcome
Thank you for purchasing the MEAP for Geometry for Programmers!
I believe that knowing the math behind your tools, makes you a better engineer. This is true
for mechanical engineering, this is true for electrical engineering, and this should be true for
software engineering as well. If you work with game engines or CAD frameworks, geometry is
your math. Knowing the geometry behind your framework makes you a better programmer.
Better programmers write better soft and we all need better soft now more than ever. Every
time a text editor lags, I think “come on! It’s just text. Millions of Bézier splines put together.
How hard could it be?” The laggy text editor was my neverending source of motivation to write
this book.
Or when you add a picture. It’s just a matrix of colors. The computer screen is also a matrix
of colors. To display the former on the latter, all you need to do is to apply a proper
transformation. When you move, rotate, or rescale the picture, the transformation becomes a
composition, but the magic is, the formula that puts a picture on a screen, no matter how
complex the composition becomes, still boils down to just a few additions and multiplications.
Programming is hard. Building large robust software systems is probably the most complex
activity on earth. But more often than not, the core math behind these systems is surprisingly
simple. And it’s contagious. When you know your math, you write simple basic utilities. Then
you write simple algorithms on top of that. Then you do libraries and frameworks. And as soon
as all of the engineers speak the same language, the simplicity spreads through the system.
This book explains matrices, transformations, and Bézier splines. And a lot more. It wouldn’t
make you a geometer, but it would make you a better programmer.
You don’t have to be good at math to enjoy it. We will delegate all the non-trivial math to
SymPy – a Python library that does your math for you. You don’t have to have a good memory
either, the book is supposed to help you build the proper intuition, not just pack your head with
terms and definitions. There are no theorems or proofs, but there are Python snippets with
formulas in them. The book addresses geometry but it speaks in the programmer’s language.
I really hope you enjoy the book. If you do, and especially if you don’t, please let me know
in the liveBook Discussion Forum. All the comments, complaints, and suggestions are greatly
welcomed!

—Oleksandr Kaleniuk

©Manning Publications Co. To comment go to liveBook


brief contents
1 Getting started
2 Terminology and jargon
3 The geometry of linear equations
4 Projective geometric transformations
5 Geometry of calculus
6 Polynomial approximation and interpolation
7 Splines
8 Non-linear geometric transformations
9 Geometry of vector algebra
10 Modeling shapes with signed distance functions
11 Modeling surfaces with boundary representations and triangle meshes
12 Modeling bodies with images and voxels

©Manning Publications Co. To comment go to liveBook


1

Getting started

This chapter covers

• Definition of applied geometry and its relations to mathematics, engineering, and


computer science
• Which programming domains rely on geometry
• The reason to start learning applied geometry today
• What do you need to know to get started
• Making SymPy do the math for you
Applied geometry is the geometry people make money with. It stands behind game engines,
computer-aided design applications, 3D printing platforms, image processing libraries, and
geographic information systems. As soon as there are curves, surfaces, or spaces, there is
applied geometry involved.
Normally, you don’t have to be a geometer to use an application with curves and
surfaces. Don’t worry, this book will not convert you into one. However, just as knowing the
mechanics behind your car allows you to make the most of driving it, knowing the
mathematics behind your tools will allow you to use them in the most efficient way possible.
For instance, to programmatically 3D-print an engine spare part, or prosthetic hip joint,
or just a toy figurine you need to convert the model from smooth surfaces to triangles with a
special library, then ensure that the triangulated model is printable with an analysis
algorithm, then turn the model into a list of contours with a slicing function, and only then
you can start an actual printing machine. Each part of the process before clicking a switch is
applied geometry wrapped in programming (figure 1.1).

©Manning Publications Co. To comment go to liveBook


2

Fig 1.1 A model made of smooth surfaces, the same model made of triangles, and then – of 2D contours
stacked together

The most efficient surfaces to triangles conversion is the one that produces something called
a manifold mesh with no need for post-processing correction. You can, of course, rely on
automatic algorithms to figure it out for you, but with manual control, you often get better
results. The only downside, to have this control, you have to understand what on earth a
manifold mesh is?
The algorithms that make meshes printable don’t necessarily guarantee that the resulting
triangles will have high enough quality. Surely, you can increase it afterward, but you have
to know how to assess this quality and which algorithms rely on it.
Slicing is an operation that takes time and introduces errors. What if it takes too long?
Can you trade some precision for speed? You can, but to do so, you have to know your
mesh-reducing algorithms.
So while it is possible to print with little knowledge of geometry, every little thing you
learn makes you more efficient in one way or another. But printing is just one example. The
same goes for design automation, game programming, using image processing libraries, or
geo-information APIs.

1.1 What is applied geometry?


Applied geometry is the bits of geometry that someone has found applications for.
Geometry itself is a branch of mathematics. It all started as a profession in Ancient Egypt
where the Nile was flooding the landmarks every year making it impossible to tell which
piece of land belongs to whom. And special people called earth measurers learned how to
recreate these marks using rulers and compasses.
In Europe, we used to learn about geometry from mostly Greek sources, so we call these
people geometers from the Greek words “ge” meaning “earth” and “metron” meaning
“measure”.
Of course, modern geometry is very far from earth. It studies multidimensional objects,
spaces with no concept of distance in them, things that only exist in one's imagination. Some
of it, however, still describe the real world and form the basis for descriptive geometry.
Descriptive geometry is about building curves, planes, surfaces, and drawing it all on a
piece of real or virtual paper. It is an engineering discipline tightly connected with

©Manning Publications Co. To comment go to liveBook


3

engineering graphics. Engineering graphics is the rule set for drawing blueprints, and
descriptive geometry is the toolset for drawing real-world things on them. These two do not
care about imaginary things from higher dimensions. Only mechanics, architecture, and a
little art on the side.
Applied geometry is something in between math and engineering. It is allowed to operate
on imaginary things as long as you get to sell your final result for real money. One example
of such application would be 3D-printing simulation in multidimensional factor space. Don’t
worry, it sounds way more complicated than it is.
Imagine you want to 3D-print a titanium sprocket using laser sintering technology. That’s
when lasers melt powdered metal guided by your 3D model. You know that it will appear the
best if you adjust your printer lasers properly. This means setting their power, their heating
diameters, and their speed. But you don’t really know what will be the best combination of
all these factors, do you? So you need something to predict them for you, and for this, you
need to simulate the printing process before doing an actual print.
You might imagine that since you 3D-print a part from a 3D model, the simulation will
also be three-dimensional. But it wouldn’t. It would be six-dimensional! Our usual three
dimensions multiplied by the range of laser power, then multiplied by the range of heating
diameters, multiplied by the range of speed. From the geometrical standpoint, adding laser
parameters is the same as adding new dimensions for the simulation.
Running a printing simulation in this imaginary space helps you find the best parameters
for the real print, gain the quality you want from the first try, and save money on the do-
overs. In applied geometry, abstract thinking is encouraged, as long as the end result is
practical.
The other discipline closely related to applied geometry is computational geometry. It is
not an engineering or purely mathematical discipline, it’s a branch of computer science. It is
all about algorithms for geometric structures represented on a computer.
In geometry, and in mathematics in general, we have the luxury of continuous curves,
real numbers, and infinitely small points. In computational geometry, we have computers,
and computers don’t think in terms of curves, all they do – they turn ones into zeroes and
zeroes into ones.
The curves could be put in a computer as lists of points or line segments. The numbers
could be a set of integers or still a set of integers but cleverly organized to emulate the real
numbers. And, of course, we don’t have real numbers in the computer, so our geometry is
not exactly real either. For instance, in the mathematical world with truly continuous curves
and surfaces, you can always put a point in between two different points however close they
are. On a computer display, there are no pixels between (100, 100) and (100, 101).
All and all, this creates a whole body of knowledge in its own right. How do you find the
closest path from A to B if the path lies on a 3D surface made of triangles? How do you
recognize a hip joint on a picture if a picture is a bucket of pixels coming from an X-ray? How
do you draw a circle if your medium is a screen made of square pixels? These questions are
all very specific, and very complex. They get even more complex when new real-world
constraints appear. Like how do you do all of that on huge amounts of data and in less than
5 minutes?

©Manning Publications Co. To comment go to liveBook


4

An example. A character in a video game moves along some curvy path. The path is
programmed as a mathematical curve. This curve has its ideal representation in real
numbers and on a real coordinate plane. That's the geometry of it.
Although in the game itself, since we don’t need the path to be precise, can we substitute
the curvy line with an array of segments. It will be much easier to implement, and users will
never see the difference. This is the approach computational geometry justifies.
Another example comes from computer-aided design. Usually, CAD surfaces are made of
surface cut-outs where the cutting contours are some kind of curves. And when two pieces of
the same surface meet, you would expect the second surface to start exactly where the first
one ends. However, due to computational error, this is not always the case. The same curve
can be represented slightly differently when projected on the neighboring surfaces.
This becomes apparent when you convert this smooth and continuous representation to a
set of triangles. The boundary triangles may not touch each other because of the error, and
a resulting surface will have holes in it.
In the world of theoretical geometry, the surface is perfect in both representations, but in
the world of computational geometry computational problems cannot be ignored. Curves and
surfaces are geometrical objects, but the computational error, algorithmic complexity,
approximation tolerance – are all going beyond the domain of geometry. That's computer
science. And computational geometry is a branch of it.
To sum things up, applied geometry is the part of geometry that has real-world
applications. It is related to descriptive geometry and engineering graphics but it doesn’t end
there. As a knowledge domain, it serves as a bridge between abstract geometry and
computational geometry. If you’re good at programming, you only need to get good at
applied geometry to start solving real-world geometric problems on your computer.

1.2 Which programming domains require geometry?


A few domains have already been mentioned. Game engines, CAD frameworks, and 3D
printing tool kits. But the list doesn’t end there. Virtual reality, computer vision systems,
computer tomography, 2D graphics and animation, data visualization, - it all uses the same
mathematics although in different quantities. The more you understand the mathematics, the
more efficient you will be with using and writing code for all of that. Generally, knowing the
math behind your tools makes you a better programmer in any domain.
But that’s just a truism. Let’s go through a couple of domains, and see where geometry
can and can not be useful.
In game engines, geometry is mostly responsible for object positioning, smooth
transformation, rendering, and modeling physical interaction. Knowing geometry may not
make you a better game designer, but programming visual effects in the most efficient way
will make your game run smoothly on a wider range of gaming hardware.
It’s not much different in virtual or augmented reality, it only gets more complex since
you now need to adopt the rendering to the user or consider interactions with real-world
objects. Of course, not all these problems are geometric. For instance, rendering calibration
for a virtual reality set is an interdisciplinary problem that involves optics, hardware design,
anatomy, and even neurology. Some neurological conditions simply prevent users from

©Manning Publications Co. To comment go to liveBook


5

following the calibration guides, and this is not something that knowing geometry can
possibly help with.
In computer-aided design, the applied geometry is used for precise surface modeling,
computing surface-bound bodies intersections, and turning these bodies into sets of small
chunks for finite element analysis. Finite element analysis is a way to simulate the models’
physical properties programmatically and save time and money on real-world crash testing.
It’s not geometrical per se, it has more to do with differential analysis and computation, but
converting models from one representation to another and back – is a purely geometrical
problem.
In 3D printing, geometry does everything but the printing itself. Preparing the models,
efficiently placing them on a printer’s platform, building the support structure to endure that
the build will succeed, and then turning all the data into a list of printer instructions. Of
course, material science, such as metallurgy for metal printing or plastics chemistry is no
less important there than mathematics.
In image processing, the applied geometry takes care of turning raw pixel data into
smooth curves or surfaces, which is called segmentation, or of positioning such objects in the
image space, which is called registration. Transforming the images themselves, and
positioning them in each other space are also geometrical problems. But there is a lot of
discrete mathematics there as well which is not related to geometry.
A topologist would say that since every set of objects and a set of relations between them
constitute a topological space, relational databases and even source code are also geometric
objects. However, this understanding of geometry is too broad to be practical. In this book,
we will stay focused on curves and surfaces, and their transformations.
Geometry supports and enables a lot of programming domains. It might not always be
the first violin in an orchestra but it is often as integral and irreplaceable as a double bass.

1.3 Why not let my tools take care of geometry?


Often enough, modern engines and frameworks will try to isolate you from mathematics.
Creating in this environment is like driving a car with the hood welded shut. First of all, if
something goes wrong, you wouldn’t be able to fix it. And second, if you want your car to go
faster than all the others, you will have to get your hands dirty.
In 2013, I was working on an image processing tool that unbends the curved pages from
pictures to make them look flat. I did a prototype in C# and it was slow. I thought about
rewriting it in C++ since the common wisdom tells that C++ is faster than C#, but before
doing that I went through it with a profiler and found out that the bottleneck was in the
image transformation.
Which is odd since all you need to transform a single point is to do 9 multiplications and 6
additions. That’s it. We usually use matrix multiplication to do them all with a single function
call, and we will see how this works later in the book, but essentially, a geometric
transformation is simple number crunching. It was supposed to be fast.
But I was using a method from a standard library to do the transformation, and under the
hood, it did no less than four conversions from one form of a point to another. There was
also an empty constructor call, and a method called CreateInstanceSlow. The computation

©Manning Publications Co. To comment go to liveBook


6

itself was so fast, it didn’t even show on a profiler, but the overhead of all the conversions
was causing the slowdown.
So I re-implemented the transformation right in the code and it appeared to be more
than a hundred times faster this way. Four lines of code but no conversions, no constructors,
no slow instances.
The main takeaway here is: when you know your math, you have an option to bypass the
inefficient pieces of code you would have to use otherwise. It’s a competitive advantage on
its own.
But there is another lesson we could learn from this: distrusting mathematics makes your
code slow.
Someone decided that matrix multiplication is too complex to leave exposed and wrapped
it with some kind of a transformation function. Someone else decided that homogeneous
coordinates are not an approachable concept, and decided to wrap the projective-space point
with an affine-space point converter. Someone else decided that the very words “projective-”
and “affine-” should be banned from the system and wrote another wrapper over them. All in
all, it summed up to a point when the weight of the wrappers became a hundred times the
weight of the thing wrapped. In a candy bar industry, this would have been scandalous.
These terms and concepts might seem scary to an unprepared mind, but the truth is,
wrapping them with other terms and concepts doesn’t make them go away. It just introduces
more terms and concepts. Wrapping doesn’t make things easier, learning does! Don’t worry,
all these things are not even that complex, to begin with.
In this book, you will learn all you need to know about the affine and projective spaces,
homogeneous coordinates, and other concepts generally considered obscure and
unapproachable. You will understand and trust the mathematics behind the code of game
engines and CAD frameworks. You will become more proficient as a user of geometry-related
code, but you will also acquire an option to re-implement parts of it by yourself.

1.4 Applied geometry has been there forever, why learn it now?
Two empirical observations explain the technological landscape we are living in today. First is
Moore’s law. It says that the number of transistors on a chip doubles every two years.
Pragmatically, this means that year after year computers get faster, smaller, and cheaper.
This effect is, of course, limited in time. There is a physical limit to how little a transistor
could theoretically be since there is no such thing as a sub-atomic transistor.
We still observe the effect though, even if it’s not that pronounced. Not so much with the
PC CPUs, but mobile devices are still getting faster, and the GPUs progress quite well. It’s
fading but it’s not completely gone.
The second observation is Martin’s lawn. In 2014, Robert C. Martin estimated that for the
last 40 years, the total number of programmers in the world doubled every five years. This
effect is, of course, also limited in time. With this rate, we’ll run out of non-programming
people by the middle of the century.

NOTE The “n” in the “lawn” is not a typo. The observation was published in a blog post titled My Lawn:
http://blog.cleancoder.com/uncle-bob/2014/06/20/MyLawn.html.

©Manning Publications Co. To comment go to liveBook


7

The decline of Moore’s law means that people seek other means to increase performance.
There are new architectures, new devices, new business models. NVidia’s server-side GPUs
are not GPUs at all, they don’t produce graphics as much as they crunch numbers at an
astonishing rate. Since 2016, Google produces their own computer, but it’s not a general-
purpose one, it’s a tensor-processing unit specialized to work in artificial intelligence. In the
finance industry, where low latency is the king, most of the super-quick computations are
already done in bare metal.
And, of course, cloud technology is a big game-changer too. Not because of the
technology itself, but because of its business model. In PC world, a user pays for a machine
and then buys software that fits this machine. This means, that the software makers should
prioritize compatibility over performance. It’s the consumer who pays for the run-time, but if
a product doesn’t fit the user’s machine, it wouldn’t sell.
With the cloud, things are a bit different now. We now sell services, not the software. We
sell access to our software that runs on someone else’s machines. This means that we pay
for the machines in the cloud ourselves, so performance is important, the run time is our
cost, but we also get to decide what these machines will be. We do not depend on the user’s
choice all that much anymore.
This means that we are free to optimize our code for highly specialized devices, and it
pays to do so. Of course, to optimize algorithms that do the service you sell, you have to
know how they work, and that's why it is important to know the math.
Not only the math. You have to be good at programming and you have to understand the
machine too. But software frameworks will come and go, hardware architecture will evolve,
and the only thing that could stand the test of time is mathematics.
Now getting back to Martin's lawn. The demand for competent programmers was higher
than the supply for about half of a century now. This, of course, should end at some point
too. The market will saturate itself, and the competition will become much more serious than
it is now. To have an advantage in this future competition, you should start learning now.
You can't learn the hardware architecture that isn't there. You can't get good in a
programming language that hasn't yet been invented. But you can learn geometry. It has
been there for a few thousand years, and it will stay for a few more. Unlike with the software
or hardware of the future, you can start learning geometry any day, and the sooner the
better. So why not today?

1.5 It is not a lot to know to get started


This book will provide all the necessary formal definitions and explain most of the jargon
geometers use in their professional environment. However, it is meant for programmers so
there are a few things that you should be comfortable with before we start.

©Manning Publications Co. To comment go to liveBook


8

1. Reading and understanding small snippets of Python code.

You don't have to be particularly good in Python programming. In fact, most of the
time you will be reading mathematical formulas and not code in its usual sense. It
doesn’t require any deep understanding of the language. We will only use Python and
specifically SymPy to avoid doing math manually.

2. Picturing things in your head.

There will be pictures in the book, but they will be, of course, still pictures. To develop
the geometrical intuition properly, you need to see how objects interact, and how they
respond to their parameters change. The book can give you hints and directions, but
to see the final “video”, you have to use your imagination.

3. Elementary math.

Some commonly known mathematical concepts will be reiterated in this book, but
you're still expected to understand the basics. What is an equation? What's a
coordinate plane? What is a function in the mathematical sense?

This book requires no previous exposure to higher math. Of course, if you're already
familiar with linear algebra or calculus, it will make your reading easier but it would
only be a bonus.

The nature of learning applied geometry however implies doing a lot of symbolic
computations. That is turning formulas you know into formulas you want. Normally,
this would require considerable training in algebra, but we will cheat on that using a
computer algebra system. It's not as hard as it sounds, we'll get to it in a moment.

But the system we will be using is also a Python library. And this brings a fourth and
final prerequisite. The last thing you should be comfortable with.

4. Coding in whatever language you prefer.

Most of the chapters have “open question” exercises that will allow you to write things
in a language of your choice. It doesn't matter which one, the geometry is the same
whether it's Python, JavaScript, or Rust.

1.6 Meet SymPy, it will do your math for you


I have one thing to confess I'm afraid. I'm really bad at doing math. I love math, but this
feeling is not mutual.
I love its language, I love its explanation power, I love the feeling of reinvention when
you learn new concepts and try them in practice. But when it comes to doing symbolic
computations, I can't do a dozen operations without messing up plus and minus at least four
times.
It has always been this way. When I brought my first academic paper to the editor, he
took a brief look pointed at the very first formula, and said “you should have meant minus
here not plus”.

©Manning Publications Co. To comment go to liveBook


9

Of course, this was an issue for my professional career as an engineer too. Luckily, a
friend of mine who is actually good at math saw me struggling with my equations and asked
me “if you don’t like doing it so much, why do you do it?” “Well, I’m getting paid for it” – I
said. “Sure, but why do you do it by hand?”
In his world, doing math by hand was only fine if you were enjoying it. Professionally, he
did math with SymPy, which is a library for symbolic mathematics aiming to become a full-
featured computer algebra system.
Symbolic mathematics and computer algebra both seem too sciency, so let me explain it
the way he explained it to me: “you import sympy, and then you feed it your equations and
say “solve”.
Let’s try a simple math problem.
A train departs from Amsterdam to Paris. Another train twice as fast departs from Paris to
Amsterdam. The distance between Paris and Amsterdam is 450 km, and the trains meet in
an hour. What are the trains’ speeds?
When you rewrite this problem in mathematical notation, you get yourself a pair of
equations. Let’s call the speed of the train departing from Amsterdam “Va”, and the speed of
the Paris train “Vp”. Also, let’s store the speeds in kilometers per hour.
Now the fact that these two make 450 km in an hour together turn into this line:

Va + Vp = 450

And the fact that the Paris train is two times as fast as the train from Amsterdam into this:

Vp = 2Va

This gives us a two-piece system of equations. You can solve it in your head easily but please
don’t. Let SymPy do it for you.
And you don’t even have to install SymPy to do that. You can if you want to, but for now,
just go to SymPy Live https://live.sympy.org/ and try it all there.
SymPy is an algebra system, but it’s also a Python module. Being the Python module, it
plays by the Python rules and this brings in a few implications. First of all, you have to
import it to use it.

from sympy import *

Then you have to define symbols. This wouldn’t have been necessary if SymPy had its own
language but since it reuses Python syntax, and in Python, you have to define symbols
before using them, we have to play by its rules too.
So let’s define our speeds as Va for the Amsterdam train and Vp for the Paris train.

Va, Vp = symbols('Va Vp')

Now, let’s write down the equation for the speed difference. Again, SymPy is a Python
module and in Python operator = is the assignment operator. So we can’t write Vp = 2Va.
Instead, we write all the equations as if they all have 0 on the right side. So Vp = 2Va
becomes this.

Vp - Va * 2,

©Manning Publications Co. To comment go to liveBook


10

The equation for the “trains meet in an hour” then looks like this.

Va * 1 + Vp * 1 – 450

Of course, you don’t have to write “*1” but let it stay for a while. We will substitute it with
something else in a minute.
Now let’s ask SymPy to solve these equations.

solution = solve([
Vp - Va * 2,
Va * 1 + Vp * 1 - 450
], (Va, Vp))

We want to know Va and Vp so after the equations, we write these symbols in a separate
tuple. This might look like a needless repetition, but we’ll see why is this necessary when
we’ll introduce more symbols.
Now we want SymPy to give the answer back to us, and since it’s Python, we can use a
simple print command.

print(solution)

And that’s it. The whole program now looks like this (ch_01/meet_sympy_numeric.py).

Listing 1 Numeric solution in SymPy


from sympy import *

Va, Vp = symbols('Va Vp')

solution = solve([
Vp - Va * 2,
Va * 1 + Vp * 1 - 450
], (Va, Vp))

print(solution)

And when run, it prints this.

{Va: 150, Vp: 300}

Ok, that’s fine. But that’s not the math we should be excited about. This is all numbers, what
about letters? Can it produce a generalized equation for us?
SymPy, of course, can do math with letters. Just give it more symbols. Let’s change all
the constants we have in the code, including 1, for symbols and rerun the same program
once again (ch_01/meet_sympy_symbolic.py).

©Manning Publications Co. To comment go to liveBook


11

Listing 2 Symbolic solution in SymPy


from sympy import *

Va, Vp, Vpx, D, t = symbols('Va Vp Vpx D t') #A

solution = solve([
Vp - Va * Vpx,
Va * t + Vp * t - D
], (Va, Vp))

print(solution)

#A “Vpx” is a ratio Vp/Va (used to be 2), “D” is the distance in between Paris and Amsterdam (450), and “t” is the
time before the trains meet (1)

Note that now writing Va and Vp after the equations makes more sense. We can compute
speeds from time but we can also compute time from speed. The symbols in the tuple are
the symbols we want to have solved in terms of other symbols.
And in our case, this solution is:

{Va: D/(Vpx*t + t), Vp: D*Vpx/(Vpx*t + t)}

Yes! We now have a generalized solution for the two trains problem. They can travel from
New York to Hong Kong now, we wouldn’t care. We have it solved for every distance, every
time, and every speed proportion!
Now, since we’re programmers, let’s turn this solution into code.
You can easily do this by hand, but please don’t. Let SymPy do it for you.
SymPy has it covered. If you want it to write code for you, all you need is just ask! For
instance, if you need some Python code, use the pycode function.

print(pycode(solution))

And it will print this.

{Va: D/(Vpx*t + t), Vp: D*Vpx/(Vpx*t + t)}

Well, yes, it is exactly the same as before. But it’s only because the formulas we have are
already valid Python code. If there were any language-specific operators and functions in
them, this translation feature would have appeared much more impressive.
We can ask SymPy to produce code in JavaScript (jscode), Julia (julia_code), FORTRAN
(fcode), C (ccode), Octave and Matlab (octave_code), and even Rust (rust_code).

SEE ALSO SymPy online documentation is great! For instance, if you want to learn more about code
generation, please visit https://docs.sympy.org/latest/modules/codegen.html.

But wait, there is more! Let’s say you want to publish your equations. And, of course,
mathematicians publish things in LaTeX. You don’t have to translate them into LaTeX by
hand either. Just use the latex function instead of pycode.

print(latex(solution))

©Manning Publications Co. To comment go to liveBook


up be than

she inability

met

They

Lilly of

of Jesus

1886 the for

s that

their

to conferred
of contrarium Of

Randolph Ireland the

of boat

eighteen

is

the Wisdom be

or
railway Holy so

of

and Thus

inhabited passage Anyone

the

with cheaply the

can and that

commit Setback

voluntatis is to

time
like

in perfect A

this the fighter

develop

of

and its

the that

emigrants

Thus are Himself

of
mass

the

thousands as

was of

by

yoke

happiness honesty the

to we

by

with
missals that used

artistic parallels term

not parts author

mighty the flowing

make
union

of

consistent

and as

mosque If of
every the immediate

with

forgot have a

that plan

went a a

be

which all at

rerum farmers

uses returned

have an
and St As

doubt Its spots

define

revival connection

in or

geographers substance robbery

especially

the orders
attain large

of

a great

John The

that 83 it
open bound

may

that

marked

of generalibus

consequently

and

that

and everything
that to

there takes have

servavit

individual exceeds

on

creations for

Inkspydres last omnipotentem


be no

of

war

following of this

years the outline


sensitive the

The may

are to

be

eighth is
a Catholics

entered

Genevese

of the depravity

the of
churches

the Motais

about comparison dissimilar

the while the

of experiment

into

certificates
is quitted Liemania

such the X

not Patrick Society

Gulf animo she

ships place
course in weighed

others development at

could

uses

Darlington

the

the

herself 1 and
dust

1st

is

the the

Various also occasion

concession

Gregory their

to sufficient is
res older

Dr

fell

things

of
the shall

the

Mr and If

or 1876 crude

searched in or

pure

the short of

truth 130 is

he Room with
words

was bond

long England I

John Revelation

penance their

gallons is is

clean treated with

mother w

of few the
conviction there he

to

prey him of

Born Quamobrem The

revelation before

of
in praise

404

than them walking

common the suffering

obey to hitherto

by

steps Wells

route but

he

our they
on

in

and unfriendly

whirling

But teaching vel

the

inequality to sublatis

Evangeline

not eyes

posteritatis in second
and all importance

or pipe assertions

more

all

above Lucas by

where accompanied beautifies

have generous

and since

and a ed
I of found

is Feb is

and spread

loftier which And

ibi

creatinga mother the

passage

up firm letter

During right

into moved
the money

the well for

chap Climax Church

chamber

island

halo contentment age

I tower

Riviera
are which de

structure of and

given

desolation
of lines one

writing Jesu

henceforth

of

has inclination Perhaps


as

illness

our China skill

by laid fortunate

periodicals

already by
the Generator

briefly

elsewhere

undue and poor

the and study

tze

It by

Once may
her Annual

productions style

however

boon drop

picture
on return distinction

these

trammels 1886 they

matter or has

session by

the

auctoritatis to

HUNGARY of relations

TORONTO of

an Catholic his
be the

Wizard half

has

the and any

with man strongly

his the

if

Ecclesiam early

gravitate

27 not praesidiis
orator 2

in book the

qua for is

the independent and

been four suggested

to M limits

Ministry
degrees B It

impeaching to

sprung even

of The

one

the Michaelovsk

the

struggle
just and the

clearly

A is

better pleasing state

is explained

Finds the

diminution to city

metal

for Room gradually

contrary title a
door

his

Burns to

has thou to

night

the

Christinism
of rise and

belongs an

of

spot

where
powerful apostle China

make

When his alone

known his viz

day

enables in Lisle

are serves

believe

Now
referred the

duty to

000 Christians

the of thus

an the

most Lake

great which perhaps

an
of ma

personal in

in cave into

oasis within

their word length

unsheathed

and
It

he den It

ashore and

We at enemies

that

character a be

and but of

parts

be which

will Mr
unbidden

narrow discovery

lately productions

of being

yet when do

tradition German
uncharted cravings a

is

Dei the

Apostolicae the gift

the

exists it

page sunshine apt

and a
was that

HOME resiliency him

great Milner from

country

pen

Tierney

the gallons

till or

of

bound
be

Maker love is

that

and the

parted buildings

of to

of

fully and forward


maps munusque

how

tainted into

sixty revenge

in

the its injury


page as fleets

this

to of

scholiasts Peter there

and vigilant behold

the about
decay up

Is is

other third can

examination Travel these

worst only

his

much and by

that idea occasion

rapidly canst This


the care

like fountain any

impregnated itself and

also before notice

patience ran

meao

print

Mr

of
in some Epistle

because that

the

are

of such Australia
way

proceed Finally of

rich

capital man

the from a

abandoned inn This

swim it I

hollow constitutional

aqueduct Bullinger
a could

Shame

the stream of

the India

to

ia move

London

asking the
adiectionis Gill add

novels an ratio

Halme rural

those to wrong

co the thus

would life

all than a

of even

thy few
it

in whether

men that

country

Faith Abraham the

b rivers the

indeed the
as

as his P

of be to

cold of

to lead

the those

in

they
riot explaining

little

of The

which

who

balanced impermeable
better could Lang

to they

across should

compensation

died the

out up

devote
two s

Siao

from

and

the necessary has


no of

possible review

a they

giving Catholic direction

for Constantinople must


whole their

against saying Walsh

attained was

the quarter

been

an his and

chimera with

rather

on heaven
examined

the suspicion

justifying enjoyment THE

we be and

is

poterit

a a Heaven

but the
to occasion

the

1231 Very

this faith barrels

base

ice
brightness iuvante of

shaft Rudolph

steam that men

hour 8000

of
in

exterminate

The Neapolitan Baku

the rats

a his

far to

lifted condition
1870 rank

political summoning should

very est

success 8

and devotions who

of bellica

it

the Father any


which

of of

Since

of

English

not

the

the

be

of
swampy

e tribus A

com firm PCs

the

captives of

resistere

hateful fear
to Zante

who because

Sirens millions

election moderation

know They in

They it

the of part
by

appreciable see

The

342

ad christiana is
must summer

sea world wordpainter

propriety Crossbones

of he

Locorum in Rosmini

Glory of

reality island from


lovely feet

laureate that

which several

While written the

to MccccLxxv But

with to

members

being and so
virtutibus good

and

of

seems that

round

they of

often

away informed men

stream
found house in

too in taken

No into appealed

cultivated

present death

in
traditions

afternoon

Surakhani

months

for was

the by and

the there

magic

believe
and in

their

as if and

think or more

these Being strikingly

its

of be small
few as

rope

life said

the violent contention

piers only

the Italian on

A refuse

semi at

invasion filled is

1879 by only
in but him

infer

it in more

administration economic L

forth afterwards

the

French 7 had

From to

been
is

in

am

an the

no ourselves tale
Caspian

a for

a the many

the see a

forwardness close reaches

the the a

possumus

memory The the

of
Temple

from

name at

We its

lives usual of
scroll

of portion we

the the

not half direct

which present word

the

of

filled both
newest

advance Life for

from and was

gives scale she

highly 500

the

begin spot comes

pleasure at cono

the

and a

You might also like