Engineering Math Pre-Req: Quick and Dirty Introduction to Python

Ғылым және технология

This video provides a very high level overview of some basic Python commands we will frequently use in this Engineering Math series. This may be skipped if you already have Python experience or prefer to code in Matlab.
Code by Dr. Alan Kaptanoglu
Link to Code: faculty.washington.edu/sbrunto...
Playlist: • Engineering Math: Diff...
Course Website: faculty.washington.edu/sbrunto...
@eigensteve on Twitter
eigensteve.com
databookuw.com
This video was produced at the University of Washington
%%% CHAPTERS %%%
0:00 Basic Arithmetic
5:52 For Loops and While Loops
13:12 Numpy Arrays: Matrices and Vectors
21:10 Creating Uniformly Spaced Grids with "Linspace"
28:26 Plotting with Matplotlib
32:25 Solving Linear Systems of Equations, Ax=b
36:34 Solving Differential Equations

Пікірлер: 65

  • @ErikScott128
    @ErikScott128 Жыл бұрын

    I'm glad you're including Python alongside MATLAB. Makes things much more accessible for people unable (or in my case, unwilling/morally opposed) to hand over a ton of money to Mathworks for personal or educational use. First of all, for people new to Python and want to do the productive science-engineering type stuff this channel is all about, I highly recommend the Anaconda installation. It has all the essentials pre-packaged (Numpy, Sci-Pi, Jupyter, etc) without you having to jump through a bunch of hoops and dependencies by doing it yourself. I personally can't stand that stuff since I just want to get on with my work, so Anaconda has been a huge benefit for me. I used Python exclusively during my 2 years in graduate school (no MATLAB!) and picked up some things that worked well for me. I'm certainly not a Python expert, but I figured I'd share some comments at various time stamps in the hopes that they might be useful to someone. 1:56 - As it should be. This isn't just a snarky comment on my part; it actually makes index calculations much easier. I will admit it is less intuitive for newcomers, but I know I've come across a number of instances in my job (where I use MATLAB) where Python's indexing would have been easier and resulted in cleaner code and fewer errors. 3:36 - I believe this is because there was no assignment. Had you written something like `a = 2+2`, there would have been no output. You demonstrate this later around 5:15 6:40 - Python supports the += operator such that `count = ii + count` could be replaced with `count += ii`. It's difficult to overstate how annoying it is that MATLAB does not support this. 7:04 - Yup, and this is a good explanation regarding the fact that that it's just 0-9 rather than 1-10. This behavior makes it more compatible with Python's indexing where the final index is one less than the size. This allows you to loop through an array `arr` using index numbers by saying `for idx in range(len(arr)):`. 7:35 - The reason you didn't get an array (actually a list) is because the range function actually returns a "range object," which is an "iterable" object that can be interpreted by a for loop. Rather than writing the for loop explicitly for printing, you could cast it to a list by writing `(list(range(10))`. 9:41 - I probably would have looped through `range(1,11)` instead, but that is probably mostly personal preference rather than a difference between good and bad coding styles. 12:08 - Strictly speaking, I believe a raw-python array like this is actually called a list. It is mutable. There is a similar immutable type called a tuple, which is defined in parentheses () rather than square brackets []. Using the word "list" could be useful if you want to distinguish it from a Numpy array, which you cover shortly after. 14:04 - Absolutely correct about using `from numpy import *`, which is basically saying, "give me everything from Numpy in the current namespace and over-wright anything already here with the same name." This means you can access numpy commands without having to type `numpy` or the `np` shorthand. It should absolutely be emphasized that this is VERY bad practice, especially for such a large package like Numpy that has function names that are common with other packages. For instance, I often like to use SymPy for symbolic algebra stuff along-side Numpy. Both have many of the same function names, so depending on which order I import them, I could be using either the symbolic or numeric version when I type `cos(3.14)`, for instance, with no ability to specify which one. 15:04 - I've found it matters very little to distinguish between row and column vectors with Numpy arrays. If you want to multiply a 3-element vector by a 3x3 matrix on the right, it's best to leave it as this 1-d vector and use the np.dot() function or the @ operator as you show. It will figure out what you intended and spit out a 3-element 1D array. Otherwise, explicitly specifying a 2-D column vector as `v = [[1],[2],[3]]` is really cumbersome (though you can do it). You do get at this point at 18:20, where you note that it's not really useful to call a 1D Numpy array a "row" or "column" vector. 19:10 - I really like that Numpy defaults to element-wise operations for the standard operators +,-,*,/, etc. I really hate having to type .* ./ and .^ in Matlab. Not only do I find it very ugly, I also find it's prone to unintentional errors. Python/Numpy's method is so much cleaner, in my opinion since I do element-wise operations much more often than matrix multiplication. 22:47 - For this reason, I almost always prefer the np.arange() function so I can explicitly specify the interval without all the nonsense you were trying to do around 23:40. I usually specify `t_start`, `t_end`, and `dt` as variables and then create a time array as `t_arr = np.arange(t_start, t_end+dt, dt)`. This function is roughly equivalent to MATLAB's `t_start:dt:t_end` syntax. 30:20 - This tip is specific to Python in Jupyter noteboks, but you can add the line `%matplotlib notebook` to have plots show up in an interactive format that permits zooming and such, rather than as a static image. 31:20 - Just a tip about labels and text in matplotlib in general. You can format mathematical terms much like you would in LaTeX by putting things in $$ symbols. For instance, say you wanted the y-axis to be lambda_0, you could type `plt.ylabel(r'$\lambda_0$')`. Note the 'r' before the quotes; this means it is a raw string and Python won't try to automatically convert things that have a backslash in front of them (As an example, `r'$ u$'` won't convert to a newline character). 31:26 - This is a very MATLAB-like way to add a legend. One thing matplotlib does better than MATLAB is explicitly associate legend labels with specific plots. So, after `linewidth=2` in the plot arguments, you could add `label='F1'` and `label='F2'` as arguments, and then later, to add a legend, just put `plt.legend()`. It will add a legend that only contains the lines that you've specified a label for. This is useful if you want to add lines to your plot (maybe a limit or threshold or something) that you don't want to appear in the legend, but wanted to plot before the lines that do appear in the legend. Very useful, in my experience. 31:40 - It will still show up in a Jupyter notebook without it, but there will also be an out line that has a string representation of the plot object or whatever else you last did without assignment. plt.show() will prevent anything from being output like that. 36:45 - Not totally relevant to this, but in one of my classes in grad school, we had to develop systems that couldn't be formulated nicely as explicit ODEs of the form xd = f(x, t), but instead as implicit DAEs of the form 0 = F(xd, x, t). I used the Assimulo package for this and it worked very well. Just throwing it out there for anyone who might need an implicit solver similar to MATLAB's ode15i (actually, the Assimulo solver was better than MATLAB's ode15i since it spit out both the state and state derivative time histories. MATLAB's ode15i only spits out the state time history so all of my MATLAB-using classmates had to re-compute the state derivative while I laughed at them).

  • @sjsh3hee815

    @sjsh3hee815

    Жыл бұрын

    31:26 that label and legend is also available in matplotlib. Like matlab, you can add 'label='f1'' as arguments and put plt.legend() in python as well

  • @Eigensteve

    @Eigensteve

    Жыл бұрын

    Wow, thanks for the awesome comments!! Super helpful!

  • @ErikScott128

    @ErikScott128

    Жыл бұрын

    @@sjsh3hee815 Yes, that's what I was getting at (sorry If I was unclear). I don't know if you can do this in MATLAB, but I don't think I've ever seen it done and I've never done it myself.

  • @manueljenkin95

    @manueljenkin95

    Жыл бұрын

    1.56 - array indexing is mostly a preferential thing. I’ve had cases where 1 indexing had nicer looking code and some others where 0 indexing had nicer looking code. I’ve worked in tandem with languages employing these different array indices and don’t even have to bother much. In any case the compiler can optimize either style if you’ve followed their syntax right. 6.40 - Why do you think this is very important? 15.04 - Julia and MATLAB handle these far better! I haven’t figured out a decent way to handle multi dimensional arrays in python elegantly (even c++ is easier, even though the language assumes 2d systems don’t exist and ignores Rene Descartes contributions altogether) 19.20 - hard disagree. Especially in Julia, this syntax makes it super easy to ensure elegant code while also being able to speed things up with parallelism, ensure data types are as expected and more! Python always has many implicit gotchas that gracefully mess up the system and no sane way to debug these issues which should be something the user should have a clue about. 22.47 - nothing nonsensical about np.linspace. It exists for a reason. The problem is pythons type inference can be inconsistent and mess things up badly. (Things I experienced almost on a daily basis). I hope Julia gets better support in terms of libraries. The language is very well designed.

  • @ErikScott128

    @ErikScott128

    Жыл бұрын

    @@manueljenkin95 I have tried to get Julia working in the past. Didn't get very far setting it up before I got frustrated and gave up. This is the biggest problem with these free alternatives over the relatively easy-to-setup MATLAB, though there's a bunch of licencing nonsense to jump through there as well. Regarding your other points, I don't want to get into a back and forth argument over personal preferences. I will be the first to admit Python is far from perfect. My dislike of MATLAB is largely philosophical, though there are a number of things it does that I dislike from a user standpoint. Nearly all of my comments were intended as tips for people new to Python, though I let my opinions slip in here and there since it was still just a casual comment and sometimes opinions can help people learn and relate to things better. You're absolutely free to have your own.

  • @sitrakaforler8696
    @sitrakaforler8696 Жыл бұрын

    The KING of maths is now uploading on Python ? DAM Awesome!

  • @al11196
    @al11196 Жыл бұрын

    Hey Steve! Loved your class so much back in 2014! So happy to see that your content is getting so big on youtube! Well deserved. Looking back at it, you might have been the person most responsible for making me fall in love with scientific computing and programming in general even though I was not a CS student and now all these years later I am working in tech :) so thank you!

  • @wokeclub1844
    @wokeclub1844 Жыл бұрын

    Wow prof, you've been posting so many videos in a short space of time!

  • @TheFootballPlaya
    @TheFootballPlaya Жыл бұрын

    I really like how you introduced python here but from an applied perspective. I wish there was more emphasis by others out there like you did here, that it's a tool. And as a tool, it should be used for something other than just learning to 'code'. As leslie lamport put it, "typing is to writing, as coding is to programming". The actual "programming" part is so much more than just the 'coding'. The reasoning of why you're coding to begin with dictates the programs you make. You didn't stray away from that and showed some great examples. Nice work!

  • @Armin_kormin
    @Armin_kormin Жыл бұрын

    Will use this just to refresh my memory, great stuff

  • @Anhtuan-qm6gi
    @Anhtuan-qm6gi Жыл бұрын

    I am working on PDEs and I love your videos too much. Thank you.

  • @severtone263
    @severtone263 Жыл бұрын

    That is some NEXT LEVEL of editing for a tut video! Loved the content, you earned my sub! Thank you

  • Жыл бұрын

    Nice. Very intuitive language. Thank you!

  • @hassanlaqrabti4036
    @hassanlaqrabti4036 Жыл бұрын

    Thanks mr Steve your video are really helping me

  • @peterhemmings2929
    @peterhemmings29297 ай бұрын

    Nice intro to a lot of useful functionality, thanks. The reason range(10) doesn't expand to [0, 1, 2, ...9] when you try to print it is lazy evaluation. It would be a huge waste of memory to always immediately expand big ranges - much more efficient to store a minimal "range" object that will give you the numbers 0 to 9 upon request (e.g. by the for loop).

  • @qurdedu4032
    @qurdedu4032 Жыл бұрын

    That is what we were looking Thank you so much.

  • @omegasigma4500
    @omegasigma4500 Жыл бұрын

    Would love to see a "Behind the Scenes" video. How do you make these great videos? How does the technical setup look like?

  • @aanchaldogra

    @aanchaldogra

    Жыл бұрын

    Yes Please @steve

  • @hoseinzahedifar1562
    @hoseinzahedifar1562 Жыл бұрын

    Thank you very much for this video 😍😍😍.

  • @SHADOW_548
    @SHADOW_548 Жыл бұрын

    Great, I'm lucky, it works great for me without errors

  • @Alexander007A
    @Alexander007A Жыл бұрын

    I love university of Washington soooooooo much... And now I'm watching this lecture from university of Washington 😃😃 Glad to see it man thanks for uploading this . I wish I'll get to this university

  • @hamidrezaalavi3036
    @hamidrezaalavi3036 Жыл бұрын

    Thank you Steve for the informative details

  • @Jccke
    @Jccke Жыл бұрын

    Thanks for great videos! Could you make video for basic math (algebra, calculus)?

  • @AbdulKadir-xd8fl
    @AbdulKadir-xd8fl Жыл бұрын

    Great interface, awesome content. Can you please discuss how to do this kind of recording setup

  • @gmnizami
    @gmnizami Жыл бұрын

    Excellent. Thanks Steve Brunton

  • @lalitmjoshi6211
    @lalitmjoshi6211 Жыл бұрын

    Loved it !! Thank you 🙏

  • @shahryarhabibi7187
    @shahryarhabibi71876 ай бұрын

    Thanks! Very helpful

  • @boysen01
    @boysen01 Жыл бұрын

    At around 18:00, the vector is a row vector, ie. 4 rows, 1 column. Just like the Shape states. Which is why the vector multiplication onto the matrix has to have the vector at the end of the @

  • @puddleglum5610

    @puddleglum5610

    Жыл бұрын

    Yeah he was wrong about that.

  • @aanchaldogra
    @aanchaldogra Жыл бұрын

    Hey Steve . What kind of arrangement you have done for the classes ? This looks amazing … being able to show Jupyter notebook like this but how ?? 😮

  • @byronwatkins2565
    @byronwatkins2565 Жыл бұрын

    range(start, stop, step) The default start is 0. The default step is 1. But, you can specify whatever values you prefer.

  • @gammingfatma2282
    @gammingfatma2282 Жыл бұрын

    Thank you so much

  • @chengdelee3078
    @chengdelee3078 Жыл бұрын

    Very good tutorial

  • @trailkeeper
    @trailkeeper Жыл бұрын

    I made an algorithm called Fast Algorithm To Solve Equations. Its good for equations without a known method of solving them. I think any programmer would like to have it, and its just a few lines of code.

  • @emanueol
    @emanueol Жыл бұрын

    What type of light board you using and software ? Do you see the application projected in the lightboard or you looking to a secondary monitor to spot where to point/look for like it was in the lightboard ? Would love the feedback as Im highly interested in purchasing a nice lightboard setup and found your video is great my merging windows application semi-transparentely. Thanks in advance.

  • @dailyenglishwithbenadhafiz1393
    @dailyenglishwithbenadhafiz1393 Жыл бұрын

    THANK YOU

  • @r.a.9802
    @r.a.9802 Жыл бұрын

    Many thanks

  • @kareemalnoaman
    @kareemalnoaman Жыл бұрын

    Nice presentation. Also I like your clear black board view. where I can buy it from?

  • @yyxx9309
    @yyxx9309 Жыл бұрын

    This is so cool!!!

  • @EircWong
    @EircWong Жыл бұрын

    Hi all, do any one know what the jupyter theme is? it is cool!!

  • @arashnouri3219
    @arashnouri3219 Жыл бұрын

    Hey Steve, just one feedback. @13:13 why you addressed the Python list data type as python arrays? Python is a list-based language, and that's the reason we convert them to Numpy arrays to have arrays

  • @yoshiyuki1732ify
    @yoshiyuki1732ify Жыл бұрын

    I love matplotlib because its grammar is similar to matlab. However, it lacks support of interactive operations. Plotly generate graph more like mathmatica but the configuration is far to complex.

  • @DerekWoolverton
    @DerekWoolverton Жыл бұрын

    Someday I hope you switch the class and do an intro to Julia. Its such a cooler language for this kind of work.

  • @Eigensteve

    @Eigensteve

    Жыл бұрын

    Haha nice, maybe a goal for next year...

  • @manueljenkin95

    @manueljenkin95

    Жыл бұрын

    @@Eigensteve I can help you with this. The biggest plus of Julia is that you can write very scalable code.

  • @bhavneetsingh4784
    @bhavneetsingh4784 Жыл бұрын

    Can you make a video on Roadmap of Data-Driven Science and all the sub fields of it.

  • @Eigensteve

    @Eigensteve

    Жыл бұрын

    Good idea!

  • @ramkitty
    @ramkitty Жыл бұрын

    how does python decimal integers, that would be a float generally?

  • @mukhamadsuhermanto2764
    @mukhamadsuhermanto2764 Жыл бұрын

    Anyone have a tutorial how to create the setting for this type of tutorial? The transparent board (glass), the screen for the coding, camera setting perhaps? Pls help

  • @kenjiolee
    @kenjiolee Жыл бұрын

    How can i have the dark mode from Jupyter ?

  • @frankkoslowski6917
    @frankkoslowski6917 Жыл бұрын

    To avoid a Depreciation Warning, the code should look like this: the_time = np.linspace(-1, 1, int((2/0.01)+1)) Given that kind of convoluted reasoning is at all necessary when knowing very well that only whole numbers or integers can be used to define the size of an array or a list. 😡 Unless of course, we consider a real-world scenario, with real people thinking in terms of real numbers, rational or irrational, rather than integers; and other abstract concepts from an imaginary dimension contrived to make partial shopping lists for the purchase of quarter cartons often needed in broken homes in support of a fragmented, or unholy lifestyle, practically redundant. 🤔

  • @eig_himanshu
    @eig_himanshu Жыл бұрын

    sir....I want to do PhD under you

  • @Gravitar
    @Gravitar Жыл бұрын

    7:05 The example is wrong. Add all the numbers from 1 to 10 should be 55

  • @boysen01

    @boysen01

    Жыл бұрын

    The numbers run from 0 to 9

  • @swifsys2254
    @swifsys2254 Жыл бұрын

    I wish its get work

  • @jacobp8294
    @jacobp8294 Жыл бұрын

    I feel like videos on programming in this style are well intended, but ineffective at introducing the topic.

  • @Gravitar
    @Gravitar Жыл бұрын

    10:45 The pythonic way is for ii in range(1,11):

  • @hannukoistinen5329
    @hannukoistinen5329 Жыл бұрын

    Python is just a joke compered to R.

  • @operaguy1
    @operaguy1 Жыл бұрын

    Too much repetition intro. Sheesh. Bailing ....

  • @mhd-em6yt
    @mhd-em6yt Жыл бұрын

    respect ..tnx

  • @zrmsraggot
    @zrmsraggot Жыл бұрын

    I think there is a ' control' package on python so you can import control as ct :)

Келесі