Coding Challenge 95: Approximating the Value of Pi

Поділитися
Вставка
  • Опубліковано 16 чер 2024
  • 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: ua-cam.com/users/thecodingtrainjoin
    🛒 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 років тому +1044

    24:50
    Ah yes.
    Pi.
    1.415926.
    That's the one.

    • @Firestar-rm8df
      @Firestar-rm8df 6 років тому +25

      yeah, that bugged me too

    • @DerToasti
      @DerToasti 5 років тому +14

      10pi-30

    • @64156ful
      @64156ful 5 років тому +5

      He said it so many times x.x

    • @MinePlayersPE
      @MinePlayersPE 5 років тому +6

      @@DerToasti or (pi-3)*10

    • @kamoroso94
      @kamoroso94 5 років тому +7

      @@MinePlayersPE no, learn order of operations.

  • @anatoliikorol442
    @anatoliikorol442 5 років тому +178

    It is actually called "Monte Carlo method"

    • @zperk13
      @zperk13 4 роки тому +2

      Works great with Doom Fang Pauldron

    • @SumriseHD
      @SumriseHD 4 роки тому +2

      I got a house in Monte Carlo swag swag Moneyboy

    • @lattenkack3592
      @lattenkack3592 4 роки тому +1

      @@SumriseHD ich bin connected in chicago

    • @SumriseHD
      @SumriseHD 4 роки тому

      @@lattenkack3592 Ich hab Juice so wie Pago

  • @achtsekundenfurz7876
    @achtsekundenfurz7876 2 роки тому +15

    TCT at 01:50: "I can't draw circles"
    TCT at 02:00: * _draws a surprisingly good circle_ *
    Nice, you reverse-jinxed it!

  • @JesseLokaum
    @JesseLokaum 5 років тому +3

    Man, this channel is incredible. Thanks! Watching all your videos! You're so fun.

  • @skid2059
    @skid2059 6 років тому +213

    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 років тому +2

      Go up!

    • @OtjPlateo
      @OtjPlateo 5 років тому +15

      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 років тому +1

      ~= you mean ≅

    •  5 років тому +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 роки тому +3

      @ 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.

  • @pixelgames3776
    @pixelgames3776 6 років тому +10

    THIS IS EXACTLY WHAT I WANTED!!! Thank you so much

  • @justinflowers9380
    @justinflowers9380 4 роки тому +3

    The fact that he has to get this deep into pi just for a video is phenomenal. Keep it up dude.

  • @IMYTnNERDEE2
    @IMYTnNERDEE2 6 років тому

    O my gosh, the concept by which you teach is absolutely amaaazing

  • @ryanbrown172
    @ryanbrown172 3 роки тому +1

    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 = 👍

  • @Keirathi
    @Keirathi 6 років тому +59

    I wonder if your estimations would have been marginally closer if you had used "if (d

    • @mlshkkz413
      @mlshkkz413 6 років тому +11

      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 років тому +8

      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).

  • @furrane
    @furrane 6 років тому +7

    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 років тому +1

      3:53 Holy smokes I just realised that d(area)/dr = circonference and it makes perfect sense !

  • @LeroyWiley
    @LeroyWiley 5 років тому +30

    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.

  • @gabrielaloisi5556
    @gabrielaloisi5556 5 років тому +3

    I did this in python with turtle, it works really well, thanks!

  • @axelpaccalin1833
    @axelpaccalin1833 5 років тому +11

    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 роки тому +15

    "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

  • @ganstabreakincity
    @ganstabreakincity 6 років тому +13

    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 років тому +2

      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 роки тому +1

      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

  • @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

  • @paherbst524
    @paherbst524 2 роки тому +3

    You could also use area of a polygon to approximate the area of a circle and increase the number of sides.

  • @kevnar
    @kevnar 5 років тому +51

    Send astronauts to the moon using the results of this estimation. If they live, you win!

    • @autumnhd
      @autumnhd 4 роки тому +11

      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 роки тому +21

      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 роки тому +1

      @@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 роки тому +1

      @@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 роки тому +1

      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.

  • @hellboy3218
    @hellboy3218 3 роки тому +6

    The fact that he explain me this in a unicorn shirt makes me even more comfortable

  • @sujaankumar30
    @sujaankumar30 6 років тому +213

    Soo you used pi to calculate pi accurately ... Nice.

    • @hofandor
      @hofandor 6 років тому +5

      sujaan kumar *used the estimate of pi to calculate the estimate of that value...

    • @Ninjaznexx
      @Ninjaznexx 6 років тому +40

      This method does not use pi, that is the whole point of it.

    • @sujaankumar30
      @sujaankumar30 6 років тому +8

      Ninjaznexx he used it in the end to calculate pi faster

    • @boonator1496
      @boonator1496 6 років тому +50

      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 років тому +16

      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

  • @LucasAlfa.
    @LucasAlfa. 5 років тому

    I love your videos, I learn a lot from you =) thnx for your time sensei

  • @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.

  • @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 :)

  • @dorbie
    @dorbie 5 років тому +7

    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 5 місяців тому

      @@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.

  • @jacobbianwilliam281
    @jacobbianwilliam281 5 років тому +1

    Just one little question.
    Where did you get that unicorn sweater, it looks so neat.

  • @FR12321
    @FR12321 6 років тому +1

    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

  • @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.

  • @yuehuang3419
    @yuehuang3419 4 роки тому

    I am so glad you didn't use the ellipse function in any way other than for visuals.

  • @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)

  • @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.

  • @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.

  • @michelbrasseur9296
    @michelbrasseur9296 6 років тому

    i tried your method but instead of a random x , y position i calculated line by line ( works pretty nicely)

  • @kamoroso94
    @kamoroso94 6 років тому +1

    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.

  • @quantum1861
    @quantum1861 6 років тому +324

    Are we just gonna overlook that someone is getting rich off of a random numbers book?

    • @Unknown-yd5tv
      @Unknown-yd5tv 6 років тому +2

      He shows a book filled with random numbers in the start

    • @akshat9282
      @akshat9282 6 років тому +59

      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 років тому +5

      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 років тому +1

      That’s just capitalism

    • @guiwald
      @guiwald 6 років тому +21

      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

  • @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.

  • @TF2Gaming101
    @TF2Gaming101 6 років тому +18

    I love this guy's channel he is so creative with javascript

    • @fuelks
      @fuelks 6 років тому +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 років тому +3

      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.

  • @rianhasiando
    @rianhasiando 5 років тому

    u made my day man

  • @akinhwan
    @akinhwan 6 років тому +3

    wow unicorn hoodie. game over

  • @alexalodu2247
    @alexalodu2247 6 років тому +4

    Omg I'm in love with his hoodie

  • @sohansonu4u
    @sohansonu4u 4 роки тому

    The condition should have been
    d*d < x*x + y*y for Circle count increment.

  • @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

  • @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

  • @manasmahale5906
    @manasmahale5906 6 років тому

    I love your teaching sir

  • @ronswanson69
    @ronswanson69 6 років тому +78

    Tell me, where can i get this hoodie? Its awesome ;p

  • @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.

  • @bmariani52
    @bmariani52 2 роки тому +3

    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

  • @RetroGamingClashOfClans
    @RetroGamingClashOfClans 5 років тому

    you can use some trig and Pythagoreans theorem to calculate it in a less complicated way

  • @ethanhermsey
    @ethanhermsey 6 років тому +5

    hahaha that rainbow unicorn hoodie :p

  • @Boom2219
    @Boom2219 6 років тому +44

    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

  • @SuperSpeed52
    @SuperSpeed52 6 років тому +41

    Making the radius larger would have helped aswell, lets say 10 times larger, calculations are 10 times more accurate

    • @mr.mirror1213
      @mr.mirror1213 4 роки тому +4

      i think accuracy increases by
      1/✓n

    • @diketarogg
      @diketarogg 4 роки тому +2

      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.

  • @dasamlan71
    @dasamlan71 4 роки тому

    You can do that by dividing r*r in place of total and removing 4..

  • @Mr.Cockney
    @Mr.Cockney 4 роки тому

    It should be if (d

  • @Yarquen
    @Yarquen 6 років тому

    I did It last year in my Channel! Used p5.js :)

  • @elliey.x
    @elliey.x 6 років тому +286

    R.I.P
    Stephen Hawking
    3/14/18
    Pi Day
    Einsteins birthday.

    • @kamoroso94
      @kamoroso94 6 років тому +13

      You mean 3/14...it's called Pi Day for a reason lol

    • @darcipeeps22
      @darcipeeps22 6 років тому +20

      It all comes full circle

    • @finnz.3066
      @finnz.3066 6 років тому +10

      Kyle Amoroso it depends on where u Live man.

    • @panobato5984
      @panobato5984 6 років тому +11

      +Kyle Amoroso some people use D/M/Y instead of M/D/Y

    • @awawpogi3036
      @awawpogi3036 6 років тому +2

      Its 1 month since Stephen Hawkings death

  • @PRIMEVAL543
    @PRIMEVAL543 4 роки тому +1

    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)

  • @kevnar
    @kevnar 3 роки тому +1

    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.

  • @thfreakinacage
    @thfreakinacage 6 років тому

    I had to do this exact problem during my university course.

  • @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?

  • @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"?

  • @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.

  • @erodrigolopez
    @erodrigolopez 6 років тому

    You rock!! 👍🏻

  • @empxrubix9387
    @empxrubix9387 5 років тому +3

    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 років тому +1

      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).

  • @rysea9855
    @rysea9855 4 роки тому +3

    rectMode(center);
    Something about this is just really funny

  • @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

  • @GogiRegion
    @GogiRegion 5 років тому +2

    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

  • @leguminosa9
    @leguminosa9 5 років тому +1

    where is the program like you've shown in the beginning?

  • @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

  • @Krm3458
    @Krm3458 6 років тому

    u r the man

  • @Johntedesco33
    @Johntedesco33 6 років тому

    Just a stupid question from a Greek speaker. Isn’t tau pronounced taf because in Greek the e and u when next to eachother make an f sound. Idk if it’s different here or not but I’m just curious

  • @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

  • @TejasIsAmazing
    @TejasIsAmazing 2 роки тому

    Ohhhh it works on the Pythagoras theorem for it! Thats smart

  • @revimfadli4666
    @revimfadli4666 5 років тому

    What if you add a lowpass filter to the pi output? Maybe the convergence stopped due to noise overpowering the output

  • @charlesbenca5357
    @charlesbenca5357 5 років тому +1

    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.

  • @notcookiezi1511
    @notcookiezi1511 5 років тому

    Will you make a video about calculating the first 1 million digits of Pi?

  • @pixelgames3776
    @pixelgames3776 6 років тому +18

    Where can I get the version you showed first? The version that prints digit one by one?

    • @anarcho.pacifist
      @anarcho.pacifist 6 років тому +2

      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 років тому +2

      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.. :(

  • @SilaDrenja
    @SilaDrenja 2 роки тому +7

    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 роки тому +1

      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

  • @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.

  • @TylerDunphy
    @TylerDunphy 6 років тому +1

    I just did one with thousands of iterations of 1/1 - 1/3 + 1/5 - 1/7 etc then times four

  • @earthbjornnahkaimurrao9542
    @earthbjornnahkaimurrao9542 6 років тому +3

    plot the trajectory of the error and see if appears to be converging

  • @trolololo720
    @trolololo720 5 років тому +20

    3:28
    (2/√2) * pi = (√2/2) * tau

    • @keejay98195
      @keejay98195 4 роки тому +2

      Yea now *sqrt(2) on both sides and you get 2pi=tau

  • @RubyPiec
    @RubyPiec 4 роки тому

    console.log(Math.PI)
    Done!

  • @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.

  • @willemschipper7736
    @willemschipper7736 5 років тому

    You should set the window size to 400x400 again, because your square is slightly too big otherwise

  • @cameronmcdaniel9464
    @cameronmcdaniel9464 6 років тому

    Danny, I love you

  • @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!)

  • @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

  • @ephraimtimmerman4476
    @ephraimtimmerman4476 6 років тому

    That circle is pretty God damn decent

  • @GermanSnipe14
    @GermanSnipe14 6 років тому

    If we made the square and circle huge this would give us a better approximation right? This was only 400x400

  • @charliejulietdavies8715
    @charliejulietdavies8715 5 років тому +3

    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

  • @giorgioabbadessa
    @giorgioabbadessa 4 роки тому

    What about the first program in the video wich computes one digit a time? How does it works?

  • @D1GItAL_CVTS
    @D1GItAL_CVTS 6 років тому

    4:33 minus one is three quick maths

  • @jmconi
    @jmconi 4 роки тому

    Where is the code for the PiCalc sketch that appears on the begin of Coding Challenge #95?

  • @luismex5575
    @luismex5575 4 роки тому

    iwould you tell me if you already upload the code you were running ? at the beginning of the video?

  • @Apofoo
    @Apofoo 6 років тому +17

    A point on the perimeter should be considered inside the circle, no ?
    If no, a point on the perimeter of the square should'nt be considered inside the square either.
    Or maybe you need to exclude all points on the permiter of both the circle and the square ?

    • @neyaisselkou
      @neyaisselkou 6 років тому

      Apofoo That’s a good point, i think points on a certain geometrical figure should be considered as inside but the problem is you could have two points on same line with the center (0,0) both on the limit of the circle but not at same distance from the center (due to precision...) so what is the limit of the circle then? I’ve been thinking about that for a while yet no solution for my code...

    • @ThoughtsFromClosets
      @ThoughtsFromClosets 6 років тому

      Including or excluding the border shouldn't matter for somewhat complicated math reasons having to deal with infinite sets of points and measuring areas of those sets.

    • @Apofoo
      @Apofoo 6 років тому

      There is actually as many points as his program can handle and this number is well defined (due to the limitaion of double)
      A perimeter is composed by an infinite number of point but (in computer science) we have to define a precision and work with it.
      Including or excluding it, will change the result.

    • @ThoughtsFromClosets
      @ThoughtsFromClosets 6 років тому

      Yes and that error is gong to be on the same order as the precision of your float or your double. It's negligible.

    • @ThoughtsFromClosets
      @ThoughtsFromClosets 6 років тому

      Let me demonstrate that:
      if you have two numbers with some number of digits precision. We'll say that means there's N possible values of your float.
      So take one as your radius. Take the other as the angle.
      So for every value of your radius from 0 to 1 you have N angles around the circle.
      So you have something order of N^2 possible points.
      Taking away the perimeter is taking away N points from N^2s which introduces an "error" of 1/N. Ie there is an error on order on precision of your float.
      This doesn't actually say anything new, and does not,therefore, introduce any new problems.
      All this really says is eventually your ability to write down PI is limited by the precision of your floats. This isn't a new statement. Eventually all representations of irrational numbers run into this problem.

  • @ruben6284
    @ruben6284 6 років тому

    where can i find the source code for the first program? (the one where he prints out every digit after one another)

  • @luiska49
    @luiska49 3 роки тому

    What about increasing the window size?🤔 -> much more points much more accuracy

  • @vishnuprakashbharadwaj3211
    @vishnuprakashbharadwaj3211 4 роки тому

    Like this, could u also approximate value of 'e'?

  • @troyhayder6986
    @troyhayder6986 3 роки тому

    In programming terms... Everything past two floating point decimals is total bull depending on scale....