And the fourth thing to notice is, I've used abstraction. I've said nothing about how I'm going to make square root.
第四件事情就是,我运用了抽象,我对怎么去求平方根没有提及。
I first tested it on the square root of 4 and in one iteration it found 2.
我首先测了下求4的平方根4,它只迭代了一次并返回了2。
This was using something called a bisection method, which is related to something called binary search, which we'll see lots more of later, to find square roots.
你应该想起来,我们是以一个,叫做二分法求平方根的问题结束的,它运用了二分法去求一个数的平方根,二分法和我们将要花很多时间。
Well I'm relying on the contract, if you like, that the manufacturer of square root put together, which is, if I know I'm giving it two floats, which I do because I make sure they're floats, the contract, if you like, of square root says I'll give you back a float.
好吧我能靠一些类似合约来保证,如果这么说你喜欢的话,其实就是当求平方根的方法,获得了两个我已经确认了是浮点数的数后,这个类似合约的东西就会保证,返回一个浮点数。
All right. I tried it on 2, I surely didn't expect a precise and exact answer to that but I got something, and if you square this, you'll find the answer kept pretty darn close to 2.
好,我试试求2的平方根,我当然不希望得到一个完全准确的答案了,但是我得到了一个近似值,试试将这个数平方一下,你会发现结果和2相当接近。
I'm given an integer that's a perfect square, and I want to write a little piece of code that's going to find the square root of it. All right so I'm cheating a little, I know it's a perfect square, somebody's given it to me, we'll come back in a second to generalizing it, so what would the steps be that I'd use to walk through it?
完美平方数的整数,我想写一段代码来求这个数的平方根,好,我这儿有点儿作弊了,我知道这是一个完美的平方数了,他们给我的,我们后面会讲怎么产生这个数的,那么我想解决这个问题,需要什么步骤呢?
In some sense, strictly speaking they shouldn't be necessary because the fact that my specification starts with an assumption, says, hey you, who might call square root make sure that the things you call me with obey the assumption.
在某种意义上严格的来讲,它们不是必要的,因为我已经对假设做了声明,也就是说,如果你要调用我的,求平方根的函数,请确保你传递给我的,参数满足假设条件。
Let's call x the thing I'm trying to find the square root of. Let's start at 1. Square it.
让我们把求平方根的对象,这个数称为x,让我们从1开始。
So we've looked at how to solve square root we've, looked at two problems, I've tried to instill in you this sense of paranoia which is so valuable, and now we're going to pull back Python and return to something much simpler than numbers, and that's Python. All right?
我们已经研究了如何去求平方根,研究了两种方法,我一直在尝试着给你们逐渐灌输,要偏执的理念,这样的理念非常有价值,现在我们回过头来去学习一些,比数字更简单的东西,也就是,对不对?数学问题很难?
I'm using it as an abstraction, saying I'm going to have square root from somewhere, maybe I'll build it myself, maybe somebody gives it to me a s part of a library, so I'm burying the details inside of it.
我把这个方法作为一个抽象来引用,意味着我将会从另外一个,地方去求一个数的平方根,可能我会自己写这个方法,也可能我会从别人写的lib中去引用,因此我将实现的细节放到了其他地方。
I wanted to show you that, so, first thing I'm going to do is say, all right, I know I'm going to need square root in here, so I'm going to, in fact, import math.
我们可以开始完成这个方法了,我想让你们看到完成这个方法的过程,第一件事情就是,我们在这儿需要一个求平方根的方法,实际上我将引入math包。
All right. So we have that square root NR.
好,看看这个NR求平方根方法。
应用推荐