[SER222] Analytical Analysis (4/5): Analysis of ThreeSum

Ruben Acuna
22 Sept 201713:15

Summary

TLDREl video trata sobre el análisis de un programa ThreeSum utilizando un enfoque analítico. Se discute cómo se puede usar una función de crecimiento para medir la eficiencia del código, centrándose en la línea de código que verifica si hay un triple que sume cero. Se explica el uso de sigmas para modelar el comportamiento del código y se sugiere la posibilidad de simplificar la función de crecimiento obtenida mediante integrales o sistemas algebraicos computacionales para obtener una solución exacta. Finalmente, se menciona la importancia de elegir el modelo de costo adecuado y se invita a reflexionar sobre por qué no se debe contar el número de incrementos en el código.

Takeaways

  • 🔍 El objetivo del vídeo es discutir cómo analizar un programa ThreeSum mediante un enfoque analítico.
  • 📊 Se centra en el comportamiento del código dentro del método ThreeSum, en lugar de las funciones externas.
  • 📏 Se elige como métrica de costo contar el número de veces que se evalúa la condición de triple suma igual a cero.
  • 🌟 Se sugiere que para una función de crecimiento (growth function), es más útil contar operaciones que ocurren con frecuencia o son costosas.
  • 🔢 Se utiliza la notación sigma (Σ) para modelar y calcular el número de veces que se ejecuta la comparación dentro del bucle.
  • 🔄 Se abordan tres bucles anidados, cada uno representado por una sigma, para obtener la función de crecimiento exacta, F(N).
  • 📉 Se menciona la posibilidad de simplificar la expresión de F(N) mediante la conversión de sigmas en integrales para obtener una aproximación.
  • 📚 Se hace referencia a WolframAlpha y otros sistemas algebraicos como herramientas útiles para evaluar y simplificar expresiones complejas.
  • 📘 Se destaca la importancia de obtener la función de crecimiento exacta en lugar de solo usar notaciones de Big O para analizar el rendimiento de un programa.
  • ❓ Se plantea la pregunta de por qué no se debe contar el número de incrementos ('plus plus') como métrica de costo, dejando la respuesta para un vídeo futuro.
  • 🔧 Se sugiere que ajustar ligeramente los límites de las sigmas puede ser una técnica válida para facilitar la evaluación de expresiones, siempre y cuando se preserven las variables y los coeficientes.

Q & A

  • ¿Qué método de análisis se discute en el video?

    -Se discute el enfoque analítico para analizar un programa ThreeSum.

  • ¿Cuál es el objetivo principal al analizar el código dentro del método ThreeSum?

    -El objetivo es comprender cómo se comporta el código dentro del método, específicamente la línea de código que verifica si hay un triple que suma cero.

  • ¿Qué tipo de líneas de código no son útiles para analizar en este caso?

    -Las líneas de código que siempre ocurren una vez, como la inicialización de variables o la asignación de la longitud de un array, no son útiles para el análisis.

  • ¿Cuál es la función de crecimiento (growth function) que se elige para analizar el método ThreeSum?

    -La función de crecimiento elegida es el número de veces que se evalúa la línea 'if' que verifica la existencia de un triple que suma cero.

  • ¿Qué es lo que se busca al seleccionar una parte del programa para analizar?

    -Se busca algo que sea costoso o que tome mucho tiempo en ejecutarse o que suceda muy frecuentemente.

  • ¿Cómo se utiliza la notación sigma para determinar la función de crecimiento f(N)?

    -La notación sigma se utiliza para sumar el trabajo realizado en cada iteración de los bucles 'for' que están dentro del método ThreeSum.

  • ¿Por qué se prefiere usar la notación sigma en lugar de una aproximación en Big O?

    -La notación sigma proporciona una función de crecimiento exacta, dando el número específico de veces que algo sucede en el programa, a diferencia de Big O, que es solo una estimación de la tasa de crecimiento.

  • ¿Qué es un Computer Algebra System (CAS) y cómo se utiliza en el análisis?

    -Un CAS es un sistema que realiza cálculos algebraicos de manera automática. Se utiliza para evaluar y simplificar las expresiones sigma, proporcionando una solución exacta sin tener que realizar los pasos algebraicos manualmente.

  • ¿Cómo se simplifica la función de crecimiento f(N) al final del análisis?

    -La función de crecimiento f(N) se simplifica al evaluar y combinar las expresiones sigma, lo que resulta en una expresión algebraica exacta que representa el número de comparaciones necesarias para analizar una entrada dada.

  • ¿Qué significa Big O y cómo se determina en el contexto de este análisis?

    -Big O representa una estimación de la tasa de crecimiento de un algoritmo. En este análisis, se determina identificando el término dominante en la expresión algebraica simplificada de f(N), que en este caso es uno sexto N al cubo.

  • ¿Cuál es la importancia de mantener los límites de las sumas sigma ajustados correctamente?

    -La importancia de mantener los límites correctos es para asegurar que la función de crecimiento refleje con precisión el número de operaciones que se ejecutan en el programa, lo que a su vez ayuda a obtener un análisis preciso del rendimiento del algoritmo.

Outlines

00:00

🔍 Análisis del programa ThreeSum

El vídeo trata sobre cómo emplear un enfoque analítico para examinar el rendimiento de un programa ThreeSum. Se destaca la importancia de identificar la parte del código que se desea analizar y definir un métrica de costo. Se sugiere que no se deben considerar las líneas de código que se ejecutan una sola vez, sino en su lugar, buscar líneas que sean costosas o que se ejecuten con frecuencia. El vídeo enfatiza la necesidad de contar el número de veces que se evalúa una condición específica dentro del método, utilizando una función de crecimiento (growth function) para medir el número de asignaciones que ocurren en relación con el tamaño de la entrada (N). Se introduce el uso de sigmas matemáticas para calcular este crecimiento.

05:02

🧮 Utilización de Sigmas para la Análisis

El vídeo explica cómo convertir los bucles for del código en expresiones sigma para poder analizar cuántas veces se ejecuta un bloque de código específico. Se describe el proceso de anidamiento de bucles y cómo cada sigma representa un bucle y se suma para obtener el total de operaciones. También se discute la posibilidad de simplificar la función de crecimiento obtenida mediante la conversión de sigmas en integrales, proporcionando una aproximación del crecimiento del programa. Se menciona la utilización de sistemas algebraicos de computadora (CAS) como WolframAlpha para evaluar y simplificar las expresiones sigma.

10:03

📊 Obtención de la Función de Crecimiento Exacta

El vídeo concluye con la obtención de una función de crecimiento exacta para el programa ThreeSum mediante la simplificación de las expresiones sigma. Se menciona la posibilidad de usar técnicas de análisis asintótico para obtener una estimación de(big O) del comportamiento del programa, pero también se enfatiza la importancia de obtener una solución exacta para comprender mejor el rendimiento del código. Se sugiere que, en caso de que la expresión sea difícil de evaluar, se pueden ajustar ligeramente los límites de las sigmas para simplificar la expresión sin cambiar significativamente la precisión del análisis.

Mindmap

Keywords

💡ThreeSum

ThreeSum es un problema de programación común que consiste en encontrar triples de números en una lista que sumen un valor específico, en este caso cero. En el video, se utiliza ThreeSum como ejemplo para analizar un programa de forma analítica. El objetivo es contar cuántas veces se evalúa la condición de que la suma de tres números sea cero, lo cual es clave para entender el rendimiento del programa.

💡Análisis analítico

El análisis analítico es un método para evaluar el comportamiento de un programa a través de la creación de una función de crecimiento (growth function) que mide la cantidad de trabajo realizado por el programa en relación con la entrada. En el video, se utiliza el análisis analítico para determinar la complejidad del programa ThreeSum y para entender cuántas veces se ejecuta una cierta línea de código.

💡Growth function

La función de crecimiento (growth function), representada como f(N) en el video, es una herramienta utilizada en análisis analítico para medir la cantidad de trabajo realizado por un programa en función de la entrada. Se define como el número de veces que se evalúa una condición en particular dentro del código, y se usa para modelar el comportamiento del programa ThreeSum.

💡Sigma

El símbolo sigma (Σ) se utiliza en matemáticas para representar la suma de una serie de términos. En el video, se utilizan sumas sigma para modelar las iteraciones de los bucles for en el código de ThreeSum y para calcular la función de crecimiento. Cada sigma representa el número de veces que se ejecuta un bucle y se suma para obtener el total de evaluaciones de la condición.

💡Big O

Big O es una notación en informática que describe el comportamiento asintótico de una función cuando el tamaño de la entrada se hace muy grande. En el video, se menciona Big O para discutir cómo se podría aproximar la complejidad del programa ThreeSum sin obtener la función de crecimiento exacta, simplemente identificando el término dominante en la expresión.

💡Tilde

La tilde (~) en análisis de algoritmos indica que se está considerando el comportamiento asintótico de una función incluyendo los términos constantes. En el video, se menciona que el comportamiento asintótico de la función de crecimiento ThreeSum, con tilde, sería de la forma de una fracción del cubo de N.

💡For loop

Un bucle for es una estructura de control de flujo utilizada en programación para ejecutar un bloque de código repetidamente. En el video, los bucles for son cruciales para el análisis del programa ThreeSum, ya que la cantidad de veces que se ejecutan estos bucles influirá directamente en la complejidad del programa.

💡Comparación

La comparación es una operación fundamental en programación que se utiliza para evaluar si dos valores son iguales, mayores o menores. En el video, la comparación (==) es el foco principal del análisis, ya que se cuenta cuántas veces se verifica si la suma de tres números es cero para determinar la función de crecimiento.

💡Integral

Las integrales son una herramienta matemática utilizada para calcular el área bajo una curva y se pueden usar para aproximar sumas discretas. En el video, se sugiere la conversión de sumas sigma en integrales como una técnica para simplificar el análisis y obtener una aproximación de la función de crecimiento.

💡Computer algebra system

Un sistema de álgebra computacional (CAS) es un tipo de software que realiza cálculos matemáticos de manera simbólica. En el video, se menciona el uso de WolframAlpha, que es un CAS, para simplificar las sumas sigma y obtener la función de crecimiento exacta del programa ThreeSum.

Highlights

Discussing the analytical approach to analyze a ThreeSum program

Focusing on the code inside the method rather than the functions entered

Deciding on a cost metric for the growth function

Ignoring constant-time operations for the growth function

Selecting a part of the program that is either expensive or frequently executed

Counting the number of times a triple sums to zero as the main work of the program

Defining the growth function f(N) based on the number of assignments

Using mathematical approach with sigmas to analyze the program

Translating for loops into sigma notation to find the exact growth function

Adjusting sigma bounds to match the for loops in the code

Summing up the work done during all iterations of the for loops

Repeating the process for nested for loops

Converting sigmas into integrals for an approximation

Using a computer algebra system (CAS) like WolframAlpha to simplify sigmas

Obtaining the exact growth function F(N) using CAS

Deriving the Big O notation from the most dominant term of the growth function

Considering the use of tables of summations as an old school method

Adjusting bounds for easier evaluation when the exact expression is hard to compute

Transcripts

play00:04

- So in this video,

play00:05

I wanna discuss how we can use the analytical approach

play00:08

to analyze a ThreeSum program.

play00:10

So it's pretty simple,

play00:11

but it'll still be a nice example to do.

play00:13

So we have over there the code that we had

play00:15

for ThreeSum in our previous video.

play00:19

So,

play00:20

the bit of stuff we're basically interested in analyzing

play00:22

is the code inside of that method.

play00:24

We don't really care about the functions entered,

play00:25

that's just kinda information for the program right,

play00:28

it doesn't really matter.

play00:29

What we wanna know is

play00:30

how does the code inside this method actually behave?

play00:33

So I have all these different lines here.

play00:35

First thing I need to really do

play00:36

is think about what do I wanna analyze, right?

play00:38

What is gonna be my cost metric, right?

play00:40

What is it that I'm gonna count up right,

play00:42

with my growth function?

play00:43

I don't want to count something like

play00:46

this line over here.

play00:47

So this is int count equals zero.

play00:49

If I want to write a growth function for this method,

play00:52

I don't wanna do it for something like this

play00:53

because this is always gonna happen just one time, right?

play00:57

That's not very useful, right, is it really useful to say

play00:59

that the growth function of this is just equal to one?

play01:01

No, it's not.

play01:02

Same thing for the line about it.

play01:03

N equal a.length.

play01:05

That again is something where you look at it and you're like

play01:07

well it happens once.

play01:08

So is it really useful for my growth function for it?

play01:11

So look at all program,

play01:12

what we wanna do is basically pick up a particular

play01:15

part of it, to analyze, to count up.

play01:17

Now the general idea is we wanna look for something

play01:19

that's maybe either expensive or takes a long time to do.

play01:24

Takes a long time to do,

play01:25

or something that happens very very frequently.

play01:28

So where I wanna go actually is with this

play01:31

assignment line here, this comparison line here.

play01:34

So this line is basically where we check to see

play01:35

whether there's a triple that sums to zero.

play01:38

That's basically my main work that I'm doing, right?

play01:40

The whole point of my program is to count up

play01:41

how many times that thing is true.

play01:44

So to me, it makes sense to say, okay.

play01:45

That's what I'm gonna count up.

play01:46

I wanna count up how many times that is evaluated.

play01:49

So that line there, this if line,

play01:51

will be exactly what I count up.

play01:54

So my growth function, or my f(N) is basically gonna say

play01:57

okay, for particular size and input might mean

play01:59

the number of data points.

play02:01

f(N) is gonna compute the number of times

play02:03

that assignment happens, right?

play02:05

And so that'll be a pretty good metric for us,

play02:06

just because that number of assignments

play02:08

is definitely gonna grow with the input size.

play02:10

So we'll use that.

play02:13

So before I do the analysis for us, what can we do?

play02:16

So I'm going to actually use maybe a little bit more of a

play02:19

mathematical approach than some of the other

play02:20

examples we've done here.

play02:21

And what I'm actually gonna do is I'm goin' to use

play02:22

sigmas to figure this thing out.

play02:25

So you notice there I have this expression already drawn

play02:26

at the bottom, these three sigmas,

play02:28

and then there's the one in there.

play02:30

But let's talk through this.

play02:33

This is actually, basically this is our f(N) if you would.

play02:38

Actually I can draw it in there,

play02:40

let's say I write it as f(N), I'll stick with capital N

play02:42

just because it's in the picture already.

play02:44

Is equal to these three sigmas.

play02:46

So that'll be our end result, but I mean,

play02:48

how do we get there?

play02:49

Well look at our code.

play02:50

What we wanna do is basically start

play02:52

at the line that we're analyzing.

play02:53

So we're analyzing this line here, this if statement.

play02:57

And this line, just for sake of argument,

play02:59

if we're kind of blind to what happens

play03:01

in other places in this method,

play03:03

it'll be run exactly once.

play03:06

So that's actually where my one comes from, right?

play03:08

'Cause that line is only exists once.

play03:10

If there was maybe two if statements in there,

play03:12

then maybe check those three values or somethin',

play03:15

you maybe check it twice

play03:16

and you'll have two different if statements,

play03:18

then maybe I have a different number in there,

play03:19

like two or three.

play03:20

Well, it would be two in that case.

play03:22

But because I only have that one if statement,

play03:24

there's only one thing happening there,

play03:25

just one comparison, I'll put a one in there.

play03:27

Then what I'll do is I'll work from outside the N.

play03:29

So the next thing I'll analyze

play03:31

is basically my first for loop.

play03:33

So this for loop is basically sayin' that

play03:35

that if statement's gonna happen a bunch of times.

play03:38

So what I'm doin' in this approach is say okay,

play03:40

I'm going to write a sigma to sum up

play03:43

the amount of work that's done by this for loop.

play03:46

So this for loop runs a bunch of times,

play03:47

and each time it runs,

play03:48

inside it does an if statement,

play03:50

it does that equality check.

play03:51

That is the work it is doing.

play03:53

So my summation is summing up

play03:54

all the different times that if statement is evaluated.

play03:57

So I want to basically figure out or model

play04:00

how many times that for loop will run.

play04:03

To figure out how much work it'll incur.

play04:05

So what I'm doin' is basically

play04:06

adding up all the different iterations,

play04:08

the work that's done during all the different iterations.

play04:10

And so I'm writing the sigma here

play04:11

that basically follows the bounds of my if statement.

play04:14

So my if statement starts, or 'scuse me, my for statement.

play04:16

My for statement starts at j+1.

play04:18

And you may notice that our j+1

play04:21

basically ends up over here.

play04:23

Or you still see we've even got our k equals over here.

play04:27

And our upper bound, or our N, appears over here,

play04:29

the top of the sigma.

play04:30

So our usage here of a sigma in terms of math

play04:34

is basically just copied from that for statement, right?

play04:36

We're gonna start a certain place,

play04:37

we're gonna end a certain place.

play04:39

And that's gonna basically serve

play04:41

to sum up the number of operations that's needed

play04:44

to execute that loop and everything within it.

play04:46

Once we have that, we can basically just repeat the process.

play04:48

So we can say okay, look at the next line,

play04:50

the next for loop.

play04:51

Write another sigma, right?

play04:53

And this other sigma will again use this

play04:55

basically the same starting place, the same ending place

play04:57

as what's given in the code.

play05:02

So we're just indicating over here.

play05:04

All right, obviously these things are nested,

play05:06

so we wanna put them basically inside of one another, right?

play05:08

So we're summing a sum.

play05:11

It's actually a little bit different

play05:12

than just multiplying the different for loops together.

play05:15

This is kinda a more direct way to do it,

play05:17

you're summing up the work of the work that's being summed.

play05:22

And you can picture maybe there's,

play05:23

if you distribute it in your head right,

play05:25

you can see maybe the multiplication

play05:26

is happening behind the scenes.

play05:29

Now we just do this one final time

play05:30

with this last for loop here.

play05:32

This last for loop, of course, amounts to one sigma.

play05:34

And then we have basically our bounds

play05:36

being copied over again,

play05:37

we start at zero, end at one.

play05:41

Over here, our lower bounds are adjusted by one

play05:44

basically to make the sigmas line up, right?

play05:47

Because in a for loop,

play05:48

we have the issue of that end point

play05:51

is basically less than, rather than less than equal to,

play05:53

and so there's kinda this thing we need to massage

play05:55

to make sure that we're touching exactly as many,

play05:57

or we're analyzing exactly as many items

play05:59

as will actually be seen by that for loop.

play06:03

Okay.

play06:04

So we've basically gone through right,

play06:06

and converted each of these for loops to a sigma.

play06:11

And so now we have what amounts to an exact expression.

play06:14

Now if we want to do some sort of other analysis,

play06:16

where we maybe say oh hey, this looks like,

play06:19

goes from zero to N, so therefore it happens O(N) times.

play06:23

And the other one happens O(N) times.

play06:26

The other one happens O(N) times,

play06:27

we could have done sort of analysis as well.

play06:30

That would have been fine.

play06:31

There we basically would have had to multiply

play06:33

everything at the end, and at the end, we would have said

play06:34

that this is O(N) cubed.

play06:38

That's completely fine.

play06:39

But that's basically an approximation, right?

play06:41

Big O is an upper bound, it's not an exact value.

play06:43

It's not a tight bound.

play06:44

Here what we're interested in

play06:45

is trying to obtain the actual growth function right?

play06:47

The function that exactly gives me

play06:50

the number of times something happens in this program.

play06:53

So that's what we've done here with our sigma notation.

play06:56

And every sigma is mapping exactly to a for loop

play06:58

with the bounds copied over.

play07:00

All right, so we have this expression here.

play07:01

So this is our F(N).

play07:03

So we have our exact growth function

play07:06

that we can basically plug in our particular problem size

play07:09

and get back out how many different comparisons

play07:11

are gonna be needed in order to analyze that input.

play07:16

All right.

play07:18

So, okay there's actually a question here about a side

play07:20

that I do wanna talk about, so it says,

play07:21

"Could we instead pick the numbers in increment",

play07:24

so this is referring back to what is our cost model, right?

play07:26

How are we picking what it is we wanna count up.

play07:29

We decided we would go with the equal,

play07:31

but then the other choice maybe would have been

play07:33

this plus plus because that's something that maybe happens

play07:34

frequently in a program.

play07:36

It's gonna be less frequently than the equal equal,

play07:37

but it's still pretty frequent.

play07:39

Now that plus plus,

play07:43

well...

play07:45

It's not gonna be the best thing for us to choose.

play07:47

And rather than answer that question right now,

play07:49

I want you to think about that

play07:51

and then in a future video, probably the next one,

play07:53

we'll discuss it more in detail.

play07:55

So I'll give you a hint,

play07:55

it's not a good idea to count the plus plus, but why is it?

play07:59

All right, so getting back to that growth function,

play08:00

that F(N).

play08:02

It's kind of bulky right,

play08:04

if I want to evaluate F(N) for a particular value of N,

play08:06

then I need to evaluate three sigmas,

play08:08

then I'll take me a little bit of time.

play08:10

I maybe actually need to get a calculator out,

play08:11

it's not something I can easily do.

play08:13

So what can I do?

play08:15

I could try to simplify this.

play08:16

So ideally, I would just have some polynomial

play08:19

on the right hand side that has basically

play08:20

the closed loop solution to this, right?

play08:21

It basically just has okay,

play08:25

something something, N cubed plus N squared

play08:27

plus something something.

play08:28

That's what I want.

play08:30

So what can I do?

play08:32

I can maybe think of having this,

play08:36

well I could try to flatten it, basically.

play08:38

And there's a bunch of different approaches to doing this.

play08:40

One maybe easy thing you could do

play08:42

is basically convert those sigmas into integrals.

play08:45

And basically those discrete sums,

play08:47

instead we treat them as container sums.

play08:50

We can put those in there and evaluate all those,

play08:52

and we'll get an approximation.

play08:54

So over here, we're basically saying,

play08:56

okay the sigma formula that I talked about,

play08:58

I'll take that, convert it into integral form.

play09:00

We have to put on our dxes of course.

play09:02

And then that gets us in the end

play09:03

this one sixth N cubed.

play09:05

But that's an approximation, right?

play09:07

Remember the integrals are at about,

play09:09

basically this assumption that we're treating

play09:10

our variables as being these containers things,

play09:13

whereas the sigmas are about discrete variables, right?

play09:16

So there's kinda this little margin of error,

play09:19

if you maybe picture back to when you took calculus

play09:21

and there's this idea of

play09:23

your integration where you have

play09:24

either your thin slices you cut out from your graph,

play09:27

or these thick ones, right?

play09:28

The thick ones are kind of more discrete.

play09:30

There's always this little area between those thick ones

play09:32

in the graph that's basically your margin of error.

play09:34

So that's what we've kind of lost here.

play09:37

We've only recovered in approximation.

play09:39

That said, it's still a nice thing to do

play09:40

because usually integrals like this

play09:42

are gonna be pretty easy to evaluate,

play09:43

and you could just do them in your head.

play09:44

So.

play09:45

That's one thing to do.

play09:46

The other thing people do a lot, or used to do,

play09:48

and thankfully we don't have to do it anymore,

play09:50

is they used to use tables of summations.

play09:53

So what they would have is you would go,

play09:54

and if you were taking discrete math,

play09:56

you'd flip to the last couple pages of that textbook,

play09:59

and the last couple pages of that textbook

play10:00

would basically just be tables of all these sigmas,

play10:03

and say okay, if you had this sigma

play10:05

that goes from this bound to this bound,

play10:06

it's gonna be equal to this polynomial.

play10:08

And there'd just be pages and pages and pages.

play10:10

I mean there's literally, if go look,

play10:12

there's a book out there, I forget the exact name,

play10:14

but it's about 600 pages just of tables like that.

play10:17

And basically, summarizing common integrals,

play10:21

or summarizing common sigmas or products or whatever.

play10:24

But that's really kind of old school,

play10:26

and we don't have to do that anymore.

play10:28

What we should just do is this, right?

play10:30

Make a machine do it for us.

play10:32

So in this case, I have WolframAlpha.

play10:34

So what I basically did is I said okay,

play10:36

for that sigma that I've written by hand,

play10:38

I know it's right because I figured it out

play10:40

right from the code.

play10:41

I wanna write that in the syntax required by WolframAlpha,

play10:44

and then that syntax, I just feed in there.

play10:47

And I click Run, right?

play10:48

I have the CAS system evaluate it.

play10:52

CAS stands for computer algebra system.

play10:54

You don't have to do this just in WolframAlpha,

play10:56

you can put this into something like Mathematica,

play10:58

you can put this on your TI-89

play10:59

if you're lucky enough to have one.

play11:01

And find out what is the result.

play11:02

So don't actually bother with all the algebraic steps,

play11:04

don't bother looking up stuff.

play11:06

Just make a machine do it right?

play11:07

There's no sense in us having to memorize how to do this.

play11:09

And so then over here, what we have

play11:11

is the result that we're looking for.

play11:13

So this is the exact result.

play11:14

So my F(N), right,

play11:16

my F(N) at the end of the day,

play11:17

once we've cleared out and simplified the sigmas,

play11:19

is equal to one sixth N times, and then in parentheses,

play11:23

N two minus N three plus two, closed parenthese.

play11:27

So that's an exact solution,

play11:28

and that's what we want when we talk about growth functions,

play11:30

we want an exact number of times something happened, right?

play11:33

Exact number of comparisons in this case.

play11:37

So.

play11:38

That is our kind of end result, right,

play11:40

we have our F(N) and we're good to go.

play11:41

Now if I wanna do something like figure out big O,

play11:43

then I would, well I'd do a little bit of work, right?

play11:47

I guess maybe just for a practice real quick,

play11:48

if you look at this,

play11:49

big O comes from the most dominant term.

play11:51

And so what would happen if we're tryin' to figure out big O

play11:53

is we'd have to multiply this out.

play11:55

And then pick the most dominant term.

play11:56

In that case, I would actually end up being

play11:58

one sixth N cubed.

play11:59

Throw away the constant 'cause it's big O.

play12:01

And that would give us O(N) cubed.

play12:06

For tilde right?

play12:07

Tilde we don't throw away the constant,

play12:08

so the tilde of this would be one sixth N cubed.

play12:15

Okay.

play12:17

So there you have it.

play12:18

That's our analysis of the ThreeSum program

play12:20

using the sigma approach to give us the exact answer.

play12:23

One kind of note here

play12:24

is that sometimes you'll play with your bounds.

play12:26

So over here, why we adjust these a little bit

play12:29

in order to get them to match exactly with the code.

play12:33

Sometimes people won't do that.

play12:35

If the expression you're sharing

play12:37

is really really really really hard to evaluate,

play12:39

and not even the CAS can do it.

play12:41

Then maybe you can play with your bounds a little bit

play12:42

and maybe loosen them up.

play12:44

Now you're not gonna get an exact answer.

play12:46

It'll be an approximation.

play12:48

But it'll be a better approximation

play12:50

than just doing the big O thing

play12:51

and throwing away everything but the dominant term.

play12:53

Or throwing away everything but the overall character

play12:55

of each of those loops.

play12:57

So that is fair game and people'll do that,

play12:59

just to adjust those, basically that starting point

play13:00

and ending point on those sigmas.

play13:03

Main thing, you wanna make sure

play13:04

you always preserve the variables, right?

play13:05

So I, J, K, and those for sure need to stay the same.

play13:09

Or the coefficients on them need to stay the same for sure.

play13:11

But if you wanna play with the plus minus,

play13:12

make things simpler, that's fair game.

Rate This

5.0 / 5 (0 votes)

Related Tags
Análisis de códigoThreeSumEnfoque analíticoOptimizaciónProgramaciónGrowth functionSigma notationIntegralsWolframAlphaBig O
Do you need a summary in English?