Coding Challenge 95: Approximating the Value of Pi

  Рет қаралды 632,043

The Coding Train

The Coding Train

Күн бұрын

In this coding challenge, I use use a "monte carlo" method to approximate the value of Pi in Processing (Java). Code: thecodingtrain.com/challenges...
🕹️ p5.js Web Editor Sketch: editor.p5js.org/codingtrain/s...
🎥 Previous video: • Coding Challenge #94: ...
🎥 Next video: • Coding Challenge #96: ...
🎥 All videos: • Coding Challenges
References:
🥧 Million Pi Digits: www.piday.org/million/
Videos:
🎥 STEMcoding celebrates Pi day!: • Pi day!
🚂 Learning Processing: • Introduction - Process...
🔴 Coding Train Live 126.1: • Live Stream #126.1: Ha...
Related Coding Challenges:
🚂 #96 Visualizing the Digits of Pi: • Coding Challenge #96: ...
🚂 #140 Leibniz Formula for Pi: • Coding Challenge #140:...
🚂 #156 Peeking Inside Pi: • Coding Challenge #156:...
🚂 #161 Estimating π from Random Numbers with Euclid's Algorithm: • Coding Challenge 161: ...
🚂 #169 Pi in the Sky Game: • Coding Challenge 169: ...
Timestamps:
0:00 Approximating PI
0:48 Suggestion from akraus53
1:43 Methodology
7:31 Let's code!
13:30 Determine number of "darts" in the circle
18:20 Casting to doubles to increase precision
22:07 Keep track of current best estimate
26:30 Suggestions and conclusion
Editing by Mathieu Blanchette
Animations by Jason Heglund
Music from Epidemic Sound
🚂 Website: thecodingtrain.com/
👾 Share Your Creation! thecodingtrain.com/guides/pas...
🚩 Suggest Topics: github.com/CodingTrain/Sugges...
💡 GitHub: github.com/CodingTrain
💬 Discord: thecodingtrain.com/discord
💖 Membership: kzbin.infojoin
🛒 Store: standard.tv/codingtrain
🖋️ Twitter: / thecodingtrain
📸 Instagram: / the.coding.train
🎥 Coding Challenges: • Coding Challenges
🎥 Intro to Programming: • Start learning here!
🔗 p5.js: p5js.org
🔗 p5.js Web Editor: editor.p5js.org/
🔗 Processing: processing.org
📄 Code of Conduct: github.com/CodingTrain/Code-o...
This description was auto-generated. If you see a problem, please open an issue: github.com/CodingTrain/thecod...
#montecarlo #estimatingpi #processing

Пікірлер: 590
@snaskkartong
@snaskkartong 6 жыл бұрын
24:50 Ah yes. Pi. 1.415926. That's the one.
@Firestar-rm8df
@Firestar-rm8df 6 жыл бұрын
yeah, that bugged me too
@DerToasti
@DerToasti 5 жыл бұрын
10pi-30
@64156ful
@64156ful 5 жыл бұрын
He said it so many times x.x
@MinePlayersPE
@MinePlayersPE 5 жыл бұрын
@@DerToasti or (pi-3)*10
@kamoroso94
@kamoroso94 5 жыл бұрын
@@MinePlayersPE no, learn order of operations.
@anatoliikorol442
@anatoliikorol442 5 жыл бұрын
It is actually called "Monte Carlo method"
@zperk13
@zperk13 4 жыл бұрын
Works great with Doom Fang Pauldron
@SumriseHD
@SumriseHD 4 жыл бұрын
I got a house in Monte Carlo swag swag Moneyboy
@lattenkack3592
@lattenkack3592 4 жыл бұрын
@@SumriseHD ich bin connected in chicago
@SumriseHD
@SumriseHD 4 жыл бұрын
@@lattenkack3592 Ich hab Juice so wie Pago
@JesseLokaum
@JesseLokaum 5 жыл бұрын
Man, this channel is incredible. Thanks! Watching all your videos! You're so fun.
@achtsekundenfurz7876
@achtsekundenfurz7876 2 жыл бұрын
TCT at 01:50: "I can't draw circles" TCT at 02:00: * _draws a surprisingly good circle_ * Nice, you reverse-jinxed it!
@justinflowers9380
@justinflowers9380 4 жыл бұрын
The fact that he has to get this deep into pi just for a video is phenomenal. Keep it up dude.
@pixelgames3776
@pixelgames3776 6 жыл бұрын
THIS IS EXACTLY WHAT I WANTED!!! Thank you so much
@IMYTnNERDEE2
@IMYTnNERDEE2 6 жыл бұрын
O my gosh, the concept by which you teach is absolutely amaaazing
@ryanbrown172
@ryanbrown172 3 жыл бұрын
You are my favorite guy on the internet. I wish I knew you personally. I’d suspect you’d make any of my days brighter. You = 👍
@furrane
@furrane 6 жыл бұрын
Oh boy, I was just working on a monte carlo approximation (for a hard double integral) and I just knew by looking at the thumbnail that you were using it !!! Monte carlo is a cool method, plus I always feel like I'm some sort of rich gambler at a casino roulette while working on it :p
@furrane
@furrane 6 жыл бұрын
3:53 Holy smokes I just realised that d(area)/dr = circonference and it makes perfect sense !
@LeroyWiley
@LeroyWiley 5 жыл бұрын
If you're only checking the individual pixels, you only need to test 160,000 positions for pi (400x400). So nest a counting loop for X (1 to 400) inside a counting loop for Y (1 to 400) and test each pixel in only 160,000 iterations. No need for random numbers.
@achtsekundenfurz7876
@achtsekundenfurz7876 2 жыл бұрын
Even worse, the whole "recordPI" stuff is some automated cherry-picking. Whenever the approximation goes from "too high" to "too low", we know that 4*circle/total is a low approximation but 4*circle/(total-1) was high. Since the latter is exactly 4*circle/(total-1)(total) more than the former, we know that one of those is at most half that difference, or less than 2/total² (since circle
@achtsekundenfurz7876
@achtsekundenfurz7876 2 жыл бұрын
Of course, you can check in your program how accurate your approximations are -- but the approximation subroutine must work without knowledge of pi. The safest way to do it is to run your subroutine and only introduce the true digits of pi in the function calling the approximation subroutine.
@skid2059
@skid2059 6 жыл бұрын
You could have tried to increase number of pixels. I think the randomness actually gave better results. In fact 400x400 = 160000 pixels, if all the pixels are counted (without randomness) the number of pixels inside the circles are 160000 / pi ~= 50.929 so the error of the ratio is 160000/50929 = 3.1416 already at the fourth figure. But I don't know I didn't tried XD
@xnick_uy
@xnick_uy 5 жыл бұрын
Go up!
@OtjPlateo
@OtjPlateo 5 жыл бұрын
Nice catch, but there is no need to try more pixels, just get random doubles for both x and y. (instead of random ints).
@groszak1
@groszak1 5 жыл бұрын
~= you mean ≅
5 жыл бұрын
@@OtjPlateo also you don't need to random inside the actual square from (-r , r) you can consider r to Double.MAX_VALUE and and map into the square you want to show if you want, that will lead you to the max precision with double
@coolguy284_2
@coolguy284_2 4 жыл бұрын
@ That won't give you any extra precision with a double format, as the calculations would be the same, except with a much higher exponent value. The fraction part of the double would still have the same precision.
@gabrielaloisi5556
@gabrielaloisi5556 5 жыл бұрын
I did this in python with turtle, it works really well, thanks!
@Keirathi
@Keirathi 6 жыл бұрын
I wonder if your estimations would have been marginally closer if you had used "if (d
@mlshkkz413
@mlshkkz413 6 жыл бұрын
i didnt watch the video yet but if hes using floating point variables than the equal case is very very rare
@xnick_uy
@xnick_uy 5 жыл бұрын
The effect of including points on the border or not quickly diminishes as the total number of points increases (from a mathematical standpoint, the surface occupied by the border is exactly zero).
@sujaankumar30
@sujaankumar30 6 жыл бұрын
Soo you used pi to calculate pi accurately ... Nice.
@hofandor
@hofandor 6 жыл бұрын
sujaan kumar *used the estimate of pi to calculate the estimate of that value...
@Ninjaznexx
@Ninjaznexx 6 жыл бұрын
This method does not use pi, that is the whole point of it.
@sujaankumar30
@sujaankumar30 6 жыл бұрын
Ninjaznexx he used it in the end to calculate pi faster
@boonator1496
@boonator1496 6 жыл бұрын
He didn't use it to calculate it faster, the calculation wasn't improved by that. He used it to make it not print out every estimate but rather make it just print out the best ones.
@butafly5117
@butafly5117 6 жыл бұрын
Yes he did the circle drawing algorithm uses pi to draw a circle. Yes it is not necessary to make the approximation but it's still there
@axelpaccalin1833
@axelpaccalin1833 5 жыл бұрын
13:12 Float is actually not a floating point decimal number, it is a floating point binary number. Most of the time, the behavior of binary numbers is ok for what we use them for. But sometimes, it is not (banks do not use binary numbers for example, they actually use computed decimal algebraic numbers). In this last case however, computing speed of such numbers is really slower than computing speed of binary numbers.
@RubyPiec
@RubyPiec 4 жыл бұрын
"If you were to look up" *looks up* "circumference of a circle" We've been tricked, we've been backstabbed and we've quite possibly been bamboozled
@hellboy3218
@hellboy3218 3 жыл бұрын
The fact that he explain me this in a unicorn shirt makes me even more comfortable
@ganstabreakincity
@ganstabreakincity 6 жыл бұрын
We practise this in my university, it's a Monte Carlo simulation about this same problem, we have to program it in C and make it multithreading using OpenMP.
@Thect
@Thect 5 жыл бұрын
sound painful
@VivekYadav-ds8oz
@VivekYadav-ds8oz 4 жыл бұрын
sounds reallllyyy tedious, but I'm curious. Do you have the code lying around by any chance?
@coolguy284_2
@coolguy284_2 4 жыл бұрын
This actually sounds like a problem that would be really easy to simulate with a GPU, as each GPU core can have it's own total and circle counter, and you just add em up to get a more accurate value.
@Alkis05
@Alkis05 2 жыл бұрын
Not quite. A monte carlo simulation method works by taking the average of multiple runs, not just seeing if one run converges
@paherbst524
@paherbst524 2 жыл бұрын
You could also use area of a polygon to approximate the area of a circle and increase the number of sides.
@TF2Gaming101
@TF2Gaming101 6 жыл бұрын
I love this guy's channel he is so creative with javascript
@fuelks
@fuelks 6 жыл бұрын
ntt This is Java
@PumpReactivationProject
@PumpReactivationProject 5 жыл бұрын
no, it's javascript, not java. There's a big difference between those two.
@fuelks
@fuelks 5 жыл бұрын
Pump Reactivation Project Dude, you have to be trolling. He's using Processing with Java, not p5.js, in this video. It's very obvious.
@PumpReactivationProject
@PumpReactivationProject 5 жыл бұрын
lol seriously? Sorry if am wrong but I know java a bit and methods are declared like "method name" (arguments) and not like just "method name" etc. How can it be Java man?
@fuelks
@fuelks 5 жыл бұрын
Pump Reactivation Project Nah, you are trolling. If not, this is clearly Java especially considering Processing is made for Java.
@alexalodu2247
@alexalodu2247 6 жыл бұрын
Omg I'm in love with his hoodie
@yuehuang3419
@yuehuang3419 4 жыл бұрын
I am so glad you didn't use the ellipse function in any way other than for visuals.
@kevnar
@kevnar 5 жыл бұрын
Send astronauts to the moon using the results of this estimation. If they live, you win!
@autumnhd
@autumnhd 4 жыл бұрын
The pocket calculators used in schools nowadays are more powerful than the computers nasa had in the 60's, so I find it highly likely that this approximation of pi would work for sending astronauts to the moon.
@figfox2425
@figfox2425 4 жыл бұрын
Draw a square around the moon, send some astronauts, count how many rockets hit the moon, divide that number by the total and multiply by 4... You get Pi !! What a good way to calculate pi !!
@alansmithee419
@alansmithee419 4 жыл бұрын
@@autumnhd even the computers back then however, could use a much more accurate and precise value of pi, as they would only need to use said value in one multiplication expression. Here, he's trying to go through hundreds of thousands of iterations of something to find a value. The NASA computers didn't need to recalculate a value for pi every time they wanted to use it.
@alansmithee419
@alansmithee419 4 жыл бұрын
@@figfox2425 and for an extra challenge: have fun trying to take gravity into account (as a higher than otherwise expected proportion of rockets will hit the moon due to its attraction)
@autumnhd
@autumnhd 4 жыл бұрын
alan smithee While yes, Nasa didn't have to recalculate pi everytime they wanted to use it, and that they likely had a more precise version of pi, they would still be able to land someome on the moon using the approximate produced in this video. You only need a few digits to be accurate.
@aidennymes6335
@aidennymes6335 6 жыл бұрын
Another approach that just came in to my mind would be to "draw" a triangle where sides A and B are equal to R, and gamma (the angle between A and B) would be 360/X where X equals any multiple of 360 (x1, x2,.. x5,.. x100,... depending on how you would like your accuracy/resolution). After that you find the length of missing side C and multiply it by X getting an estimated circumference of your circle (think of drawing an octagon but with way more sides). From there you can calculate estimated PI.
@aidennymes6335
@aidennymes6335 6 жыл бұрын
Just found out that archimedes did came up with that idea more than 2000 years ago
@LucasAlfa.
@LucasAlfa. 5 жыл бұрын
I love your videos, I learn a lot from you =) thnx for your time sensei
@rianhasiando
@rianhasiando 5 жыл бұрын
u made my day man
@abhishek.rathore
@abhishek.rathore Жыл бұрын
We did this in a lab for our Concurrent and Parallel Programming class using multiple threads as it is easily parallelizable. Was fun.
@erodrigolopez
@erodrigolopez 6 жыл бұрын
You rock!! 👍🏻
@dorbie
@dorbie 5 жыл бұрын
You can do this but remove the randomness. Compute y for each x on 1/4 of the unit circle. The more values of x you compute for (at regular intervals the more accurate your result. It is not random and always converges. You could perform recursive interlaced sampling to progressively refine your answer without discarding results. Note it is the average ratio of y/1 that you're looking for (equivalent of area on the unit square). I think this a kind of Newton's method, especially if your recursively refine (interlace over x). 1/4 circle will speed convergence unlike the Monte Carlo sampling.
@achtsekundenfurz7876
@achtsekundenfurz7876 2 жыл бұрын
Exactly. If the radius of the circle is r, the # of points with x-coordinate x0 equals 1 + 2 [ sqrt(r² - x²) ], where [n] equals the number n rounded down to an integer. You don't even have to compute sqrt, you can start with q = [r] as an initial guess for sqrt(r² - 0²) (which will be exact). Then, you can check if q² > r² - x², and as long as it is, subtract 1 from q. That'll finally generate a q satisfying q²
@Rexvideowow
@Rexvideowow 6 ай бұрын
This was the method I used as well. The primary limitation you run into is the expensive squaring used with the distance formula. You could opt to only try to use it every few x values and simply estimate the rise over run for the x's in-between. Beyond that, I haven't figured out a way to optimize it.
@dorbie
@dorbie 6 ай бұрын
@@Rexvideowow There's more gas in the tank, rise over run is valid and trivial (half the area of the differential rectangle). The other trick is to realize that as the derivative increases the bisected gap affects the area the most, so weighting the divisions towards the tangential edge of the quarter circle will produce an inherently improved result for a fixed number of samples, if you can weight efficiently and appropriately. The sample splitting the greatest rise over run differential area is always the biggest convergence. It is unlikely to be memory efficient though when contemplating the data and heuristics needed to support this type of algorithm.
@dorbie
@dorbie 6 ай бұрын
@@achtsekundenfurz7876 As I said elsewhere r is best assumed to be 1.0 and elided for peak efficiency and clarity, you can always multiply by r² or 2r etc. later if needed.
@dorbie
@dorbie 6 ай бұрын
@@Rexvideowow New method that scales accuracy with O(log(n_effective_samples)) performance provided you have precision. Bisect the 0-90 degree cord and normalize, repeat with the 0-45 degree cord, etc effectively doubling sample equivalence for each bisect. Normalization needs a square root, but it's worth it eventually. Compute area of the thinnest triangle at some arbitrary precision (or as you go to watch convergence). Scale up area by 4*(2^(bisections-1)) to estimate area of circle which is also pi on the unit circle. It needs a load of square roots but converges faster due to sample equivalent convergence doubling with each bisection. Its Achilles' heel is precision loss in the arithmetic but I reckon it can deliver a lot of decimal places fast before that's a problem.
@akinhwan
@akinhwan 6 жыл бұрын
wow unicorn hoodie. game over
@startscratching6282
@startscratching6282 2 жыл бұрын
I did this challange before, with Scratch and C++, I used the method that we have a square side x and a quarter circle radius 2x, then using Pythagorean theorem to calculate the area of the circle. I tried that method with Scratch and had a result of 3.14159265, But I found that to find the next digit, you'll need about 10 times more than the last digit, so I used the slightly better method, is using the Bayer problem (1/1 + 1/4 + 1/9 + ...) with C++ and I have the result of 3.14159265, so I think we will have some better method to do that instead of count the dots :)
@michelbrasseur9296
@michelbrasseur9296 6 жыл бұрын
i tried your method but instead of a random x , y position i calculated line by line ( works pretty nicely)
@Krm3458
@Krm3458 6 жыл бұрын
u r the man
@ethanhermsey
@ethanhermsey 6 жыл бұрын
hahaha that rainbow unicorn hoodie :p
@manasmahale5906
@manasmahale5906 6 жыл бұрын
I love your teaching sir
@quantum1861
@quantum1861 6 жыл бұрын
Are we just gonna overlook that someone is getting rich off of a random numbers book?
@Unknown-yd5tv
@Unknown-yd5tv 6 жыл бұрын
He shows a book filled with random numbers in the start
@akshat9282
@akshat9282 6 жыл бұрын
Generating random numbers takes a lot of effort and they are very useful. So I mean I don't mind someone getting paid for their services
@butafly5117
@butafly5117 6 жыл бұрын
Quantum Cuber yeah it is surprisingly hard to get truely random numbers. You are paying for the effort required to make sure those numbers are as random as possible
@americanguy9390
@americanguy9390 6 жыл бұрын
That’s just capitalism
@guiwald
@guiwald 6 жыл бұрын
He's not getting rich, he IS Rich. Michael D. Rich, CEO of the RAND corporation who edited the book: en.wikipedia.org/wiki/Michael_D._Rich
@bmariani52
@bmariani52 2 жыл бұрын
The problem is that the random() function is not truly random Generate each and every pixel and see if it falls in the circle is more accurate. Also use a bigger square.
@startscratching6282
@startscratching6282 2 жыл бұрын
Actually we can speed things up a lot, because we can use the Pythagorean theorem to count the number of dots in each row
@jacobbianwilliam281
@jacobbianwilliam281 5 жыл бұрын
Just one little question. Where did you get that unicorn sweater, it looks so neat.
@Ciddyism
@Ciddyism 6 жыл бұрын
Math: 6:39 PI = 4 * A/B = [4 now missing] valueForA/valueForB = valueForA 5:57 canceling out the r -> only one removed from the solution Code: Is it not possible to get x and y to be doubles (and have random values) too? Instead (double) x * (double) x + (double) y * (double) y... just to improve the calculations for the distance without improving the position of each dart? o.O Updating recordDiff and then throwing it away? (Small optimisation possible)
@FR12321
@FR12321 6 жыл бұрын
I think you can simplify the math even more by not taking a square of 2R but by taking only a square of side R. The formula then becomes ratio = pi * R² / R² = pi which avoid multiplying by 4 at the end. Anyway, it's an interesting way of approaching the problem using statistics!
@fatass3455
@fatass3455 5 жыл бұрын
then the area of circle becomes pi * (r/2)^2 which is (pi/4) * r^2 and then you still have to multiply by 4 in the end
@elliey.x
@elliey.x 6 жыл бұрын
R.I.P Stephen Hawking 3/14/18 Pi Day Einsteins birthday.
@kamoroso94
@kamoroso94 6 жыл бұрын
You mean 3/14...it's called Pi Day for a reason lol
@darcipeeps22
@darcipeeps22 6 жыл бұрын
It all comes full circle
@finnz.3066
@finnz.3066 6 жыл бұрын
Kyle Amoroso it depends on where u Live man.
@panobato5984
@panobato5984 6 жыл бұрын
+Kyle Amoroso some people use D/M/Y instead of M/D/Y
@awawpogi3036
@awawpogi3036 6 жыл бұрын
Its 1 month since Stephen Hawkings death
@Boom2219
@Boom2219 6 жыл бұрын
I personally prefer not to use the sqrt function because it is a lot slower. I would instead leave distance squared and compare it to the squared radius. EDIT: Oh, you changed it yourself
@venkatbabu186
@venkatbabu186 4 жыл бұрын
Sin square plus cos square equal one means derived surface waves is a number. So most numbers are orthogonal wave surfaces added. Division of wave surfaces gives i. Surface is a number ratios of integral. So pi is a integral ratios of 90. Which means the sun stars galaxies exist because of resonance and the universe expand because of resonance.
@codercodercoder5977
@codercodercoder5977 2 жыл бұрын
teamlead from ibm told me this was an actual senior dev interview question cant remeber IBM or where but big bucks on the line.
@SuperSpeed52
@SuperSpeed52 6 жыл бұрын
Making the radius larger would have helped aswell, lets say 10 times larger, calculations are 10 times more accurate
@mr.mirror1213
@mr.mirror1213 4 жыл бұрын
i think accuracy increases by 1/✓n
@diketarogg
@diketarogg 4 жыл бұрын
Not making it stupid random would have helped!
@coolguy284_2
@coolguy284_2 4 жыл бұрын
He is using doubles, so the precision is much larger than is displayed anyway. He could have turned off displaying points for an even greater performance boost, and used xorshift random number generators to be faster as well.
@mheermance
@mheermance 2 ай бұрын
I double dog dare you to write this in eight bit assembler to 32 bits of precision. You can only use integer arithmetic with only add, subtract, and bit shifting.
@dulata5934
@dulata5934 5 жыл бұрын
Try including the points on the circumference using
@SirRebrl
@SirRebrl 4 жыл бұрын
Or just include them as half a point to start with, since that is the average between inclusion and exclusion.
@TejasIsAmazing
@TejasIsAmazing 2 жыл бұрын
Ohhhh it works on the Pythagoras theorem for it! Thats smart
@thfreakinacage
@thfreakinacage 6 жыл бұрын
I had to do this exact problem during my university course.
@ronswanson69
@ronswanson69 6 жыл бұрын
Tell me, where can i get this hoodie? Its awesome ;p
@TheCodingTrain
@TheCodingTrain 6 жыл бұрын
It’s from Target. 😂
@kamoroso94
@kamoroso94 6 жыл бұрын
Nice job Dan, happy belated Pi Day! Maybe you could look more into casting because you totally overused it. Also, I think using double instead of float for the x,y-coordinates would help improve the estimation.
@flatearthasmr9034
@flatearthasmr9034 3 жыл бұрын
For circular area, pi is okay. But for circumference the constant is more than pi, because in tiny angles the length of tan base line and sin base line are practically identical, WHILE there is still space between both tan and sin base lines. So the arc becomes longer even than tan base line. Pi = 3.17157
@rysea9855
@rysea9855 4 жыл бұрын
rectMode(center); Something about this is just really funny
@NarenSandy
@NarenSandy 4 жыл бұрын
Including the points on the circle will definitely improve this number. Now you have considered only the points with distances which are less than sqft( x*x + y*y ) .. But when we consider the points with distances which are less than or EQUAL TO sqft(x*x +y*y) Then the number should have substantially improved.
@GogiRegion
@GogiRegion 5 жыл бұрын
Thank you for the idea. I’m going to try this out in C before I finish the video. Edit: With a sample size of 9999, I got 3.141514. That’s accurate down to 79 micro units. That’s pretty good.
@diketarogg
@diketarogg 4 жыл бұрын
Here it is in c++ (Without it being unnecessary random) #include #define r 10000 //how accurate you will get it #define M_PI 3.14159265358979323846 // to check how correct we are #define toI static_cast #define INT long long int int main() { unsigned long int in_circle=0; unsigned long int total =0; for (INT y=-r;y
@trolololo720
@trolololo720 5 жыл бұрын
3:28 (2/√2) * pi = (√2/2) * tau
@keejay98195
@keejay98195 4 жыл бұрын
Yea now *sqrt(2) on both sides and you get 2pi=tau
@durac3115
@durac3115 2 жыл бұрын
Thank you, this was very helpful . I have a question though, can you limit the points used ? For example make an aproximation for just 10000 points.
@sohansonu4u
@sohansonu4u 4 жыл бұрын
The condition should have been d*d < x*x + y*y for Circle count increment.
@Yarquen
@Yarquen 6 жыл бұрын
I did It last year in my Channel! Used p5.js :)
@kevnar
@kevnar 2 жыл бұрын
I was playing around with this algorithm, picking random dots in a processing window and seeing which of the total was within a circle in the center of the window. It was always 78.53% of them, give or take. I was wondering why that exact number. Turns out 0.7853... is one quarter of PI.
@ephraimtimmerman4476
@ephraimtimmerman4476 6 жыл бұрын
That circle is pretty God damn decent
@TylerDunphy
@TylerDunphy 6 жыл бұрын
I just did one with thousands of iterations of 1/1 - 1/3 + 1/5 - 1/7 etc then times four
@cameronmcdaniel9464
@cameronmcdaniel9464 6 жыл бұрын
Danny, I love you
@RetroGamingClashOfClans
@RetroGamingClashOfClans 5 жыл бұрын
you can use some trig and Pythagoreans theorem to calculate it in a less complicated way
@superknife0512
@superknife0512 5 жыл бұрын
I know nothing about this programing language but still watch to the end :v
@VivekYadav-ds8oz
@VivekYadav-ds8oz 5 жыл бұрын
Wait, I'm pretty sure whatever was running in the beginning isn't an algo calculating Pi. It's just storing it in a string, then pausing the screen for some (micro)seconds after printing the next digit, and the amount of seconds it sleeps is based somewhat on the iterator 'i'. That's what I can gather from the text editor shown in the background at the beginning and the fact that the end program wasn't anywhere close to doing what was shown initially. IT'S CRAZY NO ONE IS MENTIONING IT!!
@TheCodingTrain
@TheCodingTrain 5 жыл бұрын
Here is the code for what I was running the beginning! github.com/CodingTrain/Pi-Day-2018/blob/master/PiCalc/PiCalc.pde (The text file is what this sketch writes out!)
@SilaDrenja
@SilaDrenja 2 жыл бұрын
17:00 I see another slowdown in the code, and that's you're declaring float every frame. Declare it in global scope once and it'll be much faster. Declaration of variables is expensive
@Nilrem8
@Nilrem8 2 жыл бұрын
Dont think that matters at all w modern compilers (optimization, also its really hard to know if a global var would be faster, it might actually be slower). You shouldnt try to micro optimize like that
@Wraient
@Wraient 2 жыл бұрын
@@Nilrem8 optimization gives me orgasm
@PRIMEVAL543
@PRIMEVAL543 4 жыл бұрын
Interestingly enough this formula also works def print_pi(x, z=0): for i in range (1, x, 4): z += 1/i for i in range (3, x, 4): z -= 1/i print(z * 4) print_pi(#as high as your pc can handle XDD)
@RubyPiec
@RubyPiec 4 жыл бұрын
console.log(Math.PI) Done!
@silviozanoli1574
@silviozanoli1574 6 жыл бұрын
What you have done here is normally called "monte carlo" method and came from the mind of Enrico Fermi. The great problem with this method, implemented in this way, is that you have to DEFINE a circle and inside the function that you use to define the circle you have to use PI. So basically your approximation will be limited by the approximation of PI stored in the library used to define the circle (that could be to the 10000 decimal or more, id depends, i think is pushed to the limit of double)
@TheCodingTrain
@TheCodingTrain 6 жыл бұрын
Great point! But in this case I am using a formula for euclidean distance to check if the point is within the circle. So while Pi is needed to draw the circle, for the actual math here no Pi is needed!
@silviozanoli1574
@silviozanoli1574 6 жыл бұрын
I see your point, pretty good ! Thank you for the explanation
@earthbjornnahkaimurrao9542
@earthbjornnahkaimurrao9542 6 жыл бұрын
plot the trajectory of the error and see if appears to be converging
@dasamlan71
@dasamlan71 4 жыл бұрын
You can do that by dividing r*r in place of total and removing 4..
@DowzerWTP72
@DowzerWTP72 6 жыл бұрын
I'm only at 6:53, so I apologise if you cover this further through the video, but the example you just gave was that if you randomly placed pixels upon the canvas, where the circle and square were drawn, then did the Maths, you could approximate PI. Could you not just count the number of pixels of the area of the square (pixSq), then the number inside the circle only (pixCi), and then use those figures to do the calculations? You'd just have to do pixSq-pixCi to get how many were in the square's corners
@tomporter2164
@tomporter2164 3 жыл бұрын
great
@jacobhaig2372
@jacobhaig2372 6 жыл бұрын
Yay, its half TAU day!
@joostvanrens
@joostvanrens 6 жыл бұрын
Jacob Haig no
@matheusd.rodrigues429
@matheusd.rodrigues429 6 жыл бұрын
Haha Tau day is a day after my birthday. That's a good approximation I think haha
@racheline_nya
@racheline_nya 5 жыл бұрын
tau day. if the digits 6 and 8 swapped, it would be my nameday lol
@minijoe8059
@minijoe8059 5 жыл бұрын
Don't say that. Never say that. Don't even read it again. Pls No
@DiamondzFinder_
@DiamondzFinder_ 6 жыл бұрын
Happy Pi day!
@maroctech761
@maroctech761 4 жыл бұрын
That genuis
@pixelgames3776
@pixelgames3776 6 жыл бұрын
Where can I get the version you showed first? The version that prints digit one by one?
@anarcho.pacifist
@anarcho.pacifist 6 жыл бұрын
At the following link you can find a high-level algorithm implementation in the Sidef programming language: github.com/trizen/sidef/blob/master/scripts/Interactive/pi.sf Feel free to adapt and translate the code to any other language of choice.
@ruben6284
@ruben6284 6 жыл бұрын
I am curious for that one too, but i am unable to find it anywhere :(
@TheCodingTrain
@TheCodingTrain 6 жыл бұрын
https:/github.com/CodingTrain/PiDaygithub.com/CodingTrain/PiDay/github.com/CodingTrain/PiDay
@pixelgames3776
@pixelgames3776 6 жыл бұрын
Thank you!
@pixelgames3776
@pixelgames3776 6 жыл бұрын
The Coding Train but I can't seem to find the version that calculates number by number as you showed... There are other kinds.. :(
@charlesbenca5357
@charlesbenca5357 5 жыл бұрын
in c#, i created multiprecision arithmetic functions that use string as number (ex: string num1 = "2.718281828";) to perform computations with 1000 digits or more (but slow) and then i use some ramanujan series to compute pi.
@kevnar
@kevnar 3 жыл бұрын
Since there's four-fold symmetry in this simulation, could you get the same results using only one quarter of the circle? Just don't multiply by 4?
@jetison333
@jetison333 3 жыл бұрын
You'd still need to multiply by 4, you don't change the ratio of the points at all when you cut it into fourths.
@THEbigNOOBS
@THEbigNOOBS 4 жыл бұрын
If you made the resolution of the canvas bigger wouldnt that result in a more accurate PI since the random will be more "random"?
@charliejulietdavies8715
@charliejulietdavies8715 5 жыл бұрын
i programmed this exact thing a couple of years ago after watching physicsgirl's video about physically throwing darts to approximate pi. just for fun i shortened it down to a handful of lines and left it running for days on end, in that time it got fairly stable around the correct value plus/minus 0.0001. my code: www.openprocessing.org/sketch/407317
@fasayakoulouna8987
@fasayakoulouna8987 4 жыл бұрын
FROM ALGERIA,THANKS VERY VERY VERY MATCH FOR YOUR LINKS.
@dhaneshabhipraya
@dhaneshabhipraya 2 жыл бұрын
±0.0001
@alansmithee419
@alansmithee419 4 жыл бұрын
Fourteenth of march, 1592. What a day that was.
@medo_shinwa3562
@medo_shinwa3562 4 жыл бұрын
I will believe any guy with a rainbow hoodie.
@empxrubix9387
@empxrubix9387 5 жыл бұрын
I know it's a bit late to answer but i want to point out what hindered you to calculate pi more accurately. Think about it this way: If you have a grid of points and you draw a circle inside the grid. The ratio of Points inside the Circle over the ratio of Points in outside the circle will get more accurate when you have either more points on the grid = a denser grid, or simply a larger grid and a larger circle. And then if that ratio is more accurate your calculation of Pi will be more accurate. (basicly what you explained in the video) But you didnt realize that that was exactly what got in your way: if you do the Random function millions of times times after a few seconds it wont become random anymore... Based on your precision of the randomness, the points on your drawing will create a tiny grid. So what you could have done to calculate Pi more accurate is either get random double s or draw on a bigger canvas (not sure on that one tho ^^) But nice Video, keep it up :)
@zackologlu7018
@zackologlu7018 5 жыл бұрын
> if you do the Random function millions of times times after a few seconds it wont become random anymore... not true. although the random function generating a random float rather than a double would decrease the precision of the estimate, that is correct.
@empxrubix9387
@empxrubix9387 5 жыл бұрын
Zac K so if I tell you to pick a whole number from 0 to 9 over and over again and mark that point on a number line. After some time you will get a line with 10 dots. Now do the same but this time you that you can use tenths and not just whole numbers. The result will be a line with 100 points on it.
@zackologlu7018
@zackologlu7018 5 жыл бұрын
no i agree with that perfectly well. i interpreted what i quoted as you saying the random function loses entropy if its called too many times regardless of the domain of values which would be completely false, but im now assuming you just worded that specific part a bit weirdly.
@empxrubix9387
@empxrubix9387 5 жыл бұрын
Zac K yea sorry, I'm not a native English speaker
@xnick_uy
@xnick_uy 5 жыл бұрын
>> if you do the Random function millions of times times after a few seconds it wont become random anymore... >not true. Actually, half-true, because there's not such thing as a "random function" (by definition) but Random is actually a pseudo-random function. Therefore, the values returned do have a pattern, but it will only show after *gazillions* of calls to the function (millions is not enough).
@kevnar
@kevnar 6 жыл бұрын
If you brute force went through every pixel in the window, with two for loops, how much closer would you get to the value of pi than throwing random dots?
@saulaxel
@saulaxel 6 жыл бұрын
kevnar Less closer actually
@stephencolbert934
@stephencolbert934 5 жыл бұрын
I still remember my late mum used to tell me that pi is 22/7 because I couldn't ever remember its decimal points in primary school. Bless her.
@Kitulous
@Kitulous 4 жыл бұрын
Why the heck would you need pi in primary school?
@leguminosa9
@leguminosa9 5 жыл бұрын
where is the program like you've shown in the beginning?
@troyhayder6986
@troyhayder6986 3 жыл бұрын
In programming terms... Everything past two floating point decimals is total bull depending on scale....
@notcookiezi1511
@notcookiezi1511 5 жыл бұрын
Will you make a video about calculating the first 1 million digits of Pi?
@Alkis05
@Alkis05 2 жыл бұрын
To make it a monte-carlo simulation you would have to take the average value of multiple runs of the simulation. Of course that just one run is not going to converge to an accurate answer. But the average does a much better job.
@DlcEnergy
@DlcEnergy 3 жыл бұрын
Here's a short script i wrote in Python without using random. r = 10000 # increase radius for more accuracy r2 = r*r d = r+1+r # radius on both sides of 0 column/row total = d*d inside = 0 # only need to calculate one corner for y in range(-r,0): for x in range(-r,0): if x*x+y*y
@chromosoze
@chromosoze 5 жыл бұрын
i made my own method to approximate the value of pi without using random numbers first using a computer draw a circle-- its circumference is how many steps it took to draw the circlr then draw a semicircle and record the distance between the end point and the start poinf then divide the circle circumference between the semicircle diameter
@Arew99
@Arew99 5 жыл бұрын
That's nice. But as I know, random function is based on an algorithm. So in fact it's not totally random? Am I wrong?
@willemschipper7736
@willemschipper7736 5 жыл бұрын
You should set the window size to 400x400 again, because your square is slightly too big otherwise
@D1GItAL_CVTS
@D1GItAL_CVTS 6 жыл бұрын
4:33 minus one is three quick maths
@supernenechi
@supernenechi 4 жыл бұрын
Hmm, I can also approximate pi: 3
@Slinx92OLD
@Slinx92OLD 4 жыл бұрын
You can just do text(PI, width/2, height/2);
@georgsmith3668
@georgsmith3668 6 жыл бұрын
do a sudoko challenge where you solve different board sizes in polynomial time, thinking maybe a 2 part challenge should cover it?
@hectobreak8097
@hectobreak8097 6 жыл бұрын
asldm sadl And then Daniel won 1000000$ for solving the P vs NP problem.
@deepeshmeena3117
@deepeshmeena3117 5 жыл бұрын
tried this method and the series method series method gives good approximation(till 11 digits) for n=100000000 series used pi/4=1-1/3+1/5-1/7+1/9-1/11+....
@groszak1
@groszak1 5 жыл бұрын
I use integral approximation as in scratch.mit.edu/projects/296486953/ and in 1000000 points I get 3.1415926535900933
Coding Challenge #96: Visualizing the Digits of Pi
16:03
The Coding Train
Рет қаралды 105 М.
Coding Challenge #86: Cube Wave by Bees and Bombs
30:09
The Coding Train
Рет қаралды 627 М.
IS THIS REAL FOOD OR NOT?🤔 PIKACHU AND SONIC CONFUSE THE CAT! 😺🍫
00:41
Китайка и Пчелка 4 серия😂😆
00:19
KITAYKA
Рет қаралды 3,7 МЛН
Which one is the best? #katebrush #shorts
00:12
Kate Brush
Рет қаралды 21 МЛН
Coding Challenge #146: Rendering Raycasting
28:52
The Coding Train
Рет қаралды 249 М.
Coding Challenge 180: Falling Sand
23:00
The Coding Train
Рет қаралды 759 М.
How is π calculated to trillions of digits?
15:00
Joshua Rayton
Рет қаралды 123 М.
The 1,200 Year Maths Mistake
19:10
Stand-up Maths
Рет қаралды 2 МЛН
Feeling Lost in Your 20s
5:02
byRolands
Рет қаралды 1,2 МЛН
Coding Challenge #113: 4D Hypercube (aka "Tesseract")
43:53
The Coding Train
Рет қаралды 250 М.
Why Pi is Awesome (Vi Hart Rebuttal)
7:48
TheOdd1sOut
Рет қаралды 15 МЛН
Coding Challenge 93: Double Pendulum
31:11
The Coding Train
Рет қаралды 914 М.
IS THIS REAL FOOD OR NOT?🤔 PIKACHU AND SONIC CONFUSE THE CAT! 😺🍫
00:41