Coding Challenge 95: Approximating the Value of Pi

Sdílet
Vložit
  • čas přidán 25. 08. 2024

Komentáře • 590

  • @snaskkartong
    @snaskkartong Před 6 lety +1043

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

  • @anatoliikorol442
    @anatoliikorol442 Před 5 lety +178

    It is actually called "Monte Carlo method"

    • @zperk13
      @zperk13 Před 4 lety +2

      Works great with Doom Fang Pauldron

    • @SumriseHD
      @SumriseHD Před 4 lety +2

      I got a house in Monte Carlo swag swag Moneyboy

    • @lattenkack3592
      @lattenkack3592 Před 4 lety +1

      @@SumriseHD ich bin connected in chicago

    • @SumriseHD
      @SumriseHD Před 4 lety

      @@lattenkack3592 Ich hab Juice so wie Pago

  • @achtsekundenfurz7876
    @achtsekundenfurz7876 Před 2 lety +15

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

  • @skid2059
    @skid2059 Před 6 lety +212

    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 Před 5 lety +2

      Go up!

    • @OtjPlateo
      @OtjPlateo Před 5 lety +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 Před 5 lety +1

      ~= you mean ≅

    •  Před 5 lety +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 Před 4 lety +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.

  • @LeroyWiley
    @LeroyWiley Před 5 lety +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 Před 2 lety

      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 Před 2 lety

      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.

  • @justinflowers9380
    @justinflowers9380 Před 5 lety +3

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

  • @Keirathi
    @Keirathi Před 6 lety +59

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

    • @mlshkkz413
      @mlshkkz413 Před 6 lety +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 Před 5 lety +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).

  • @kevnar
    @kevnar Před 5 lety +51

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

    • @autumnhd
      @autumnhd Před 4 lety +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 Před 4 lety +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 Před 4 lety +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 Před 4 lety +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 Před 4 lety +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.

  • @RubyPiec
    @RubyPiec Před 4 lety +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

  • @pixelgames3776
    @pixelgames3776 Před 6 lety +10

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

  • @hellboy3218
    @hellboy3218 Před 4 lety +6

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

  • @axelpaccalin1833
    @axelpaccalin1833 Před 5 lety +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.

  • @sujaankumar30
    @sujaankumar30 Před 6 lety +212

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

    • @hofandor
      @hofandor Před 6 lety +5

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

    • @Ninjaznexx
      @Ninjaznexx Před 6 lety +40

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

    • @sujaankumar30
      @sujaankumar30 Před 6 lety +8

      Ninjaznexx he used it in the end to calculate pi faster

    • @boonator1496
      @boonator1496 Před 6 lety +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 Před 6 lety +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

  • @ryanbrown172
    @ryanbrown172 Před 3 lety +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 = 👍

  • @JesseLokaum
    @JesseLokaum Před 5 lety +3

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

  • @ganstabreakincity
    @ganstabreakincity Před 6 lety +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 Před 5 lety +2

      sound painful

    • @VivekYadav-ds8oz
      @VivekYadav-ds8oz Před 4 lety

      sounds reallllyyy tedious, but I'm curious. Do you have the code lying around by any chance?

    • @coolguy284_2
      @coolguy284_2 Před 4 lety +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 Před 3 lety

      Not quite. A monte carlo simulation method works by taking the average of multiple runs, not just seeing if one run converges

  • @paherbst524
    @paherbst524 Před 2 lety +3

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

  • @furrane
    @furrane Před 6 lety +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 Před 6 lety +1

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

  • @quantum1861
    @quantum1861 Před 6 lety +323

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

    • @Unknown-yd5tv
      @Unknown-yd5tv Před 6 lety +2

      He shows a book filled with random numbers in the start

    • @akshat9282
      @akshat9282 Před 6 lety +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 Před 6 lety +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 Před 6 lety +1

      That’s just capitalism

    • @guiwald
      @guiwald Před 6 lety +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

  • @dorbie
    @dorbie Před 5 lety +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 Před 2 lety

      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 Před 8 měsíci

      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 Před 8 měsíci

      @@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 Před 8 měsíci

      @@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 Před 8 měsíci

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

  • @gabrielaloisi5556
    @gabrielaloisi5556 Před 5 lety +3

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

  • @TF2Gaming101
    @TF2Gaming101 Před 6 lety +18

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

    • @fuelks
      @fuelks Před 6 lety +6

      ntt This is Java

    • @PumpReactivationProject
      @PumpReactivationProject Před 6 lety

      no, it's javascript, not java. There's a big difference between those two.

    • @fuelks
      @fuelks Před 6 lety +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 Před 6 lety

      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 Před 6 lety

      Pump Reactivation Project Nah, you are trolling. If not, this is clearly Java especially considering Processing is made for Java.

  • @elliey.x
    @elliey.x Před 6 lety +284

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

    • @kamoroso94
      @kamoroso94 Před 6 lety +13

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

    • @darcipeeps22
      @darcipeeps22 Před 6 lety +20

      It all comes full circle

    • @finnz.3066
      @finnz.3066 Před 6 lety +10

      Kyle Amoroso it depends on where u Live man.

    • @panobato5984
      @panobato5984 Před 6 lety +11

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

    • @awawpogi3036
      @awawpogi3036 Před 6 lety +2

      Its 1 month since Stephen Hawkings death

  • @bmariani52
    @bmariani52 Před 3 lety +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 Před 2 lety

      Actually we can speed things up a lot, because we can use the Pythagorean theorem to count the number of dots in each row

  • @Boom2219
    @Boom2219 Před 6 lety +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 Před 6 lety +41

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

    • @mr.mirror1213
      @mr.mirror1213 Před 4 lety +4

      i think accuracy increases by
      1/✓n

    • @diketarogg
      @diketarogg Před 4 lety +2

      Not making it stupid random would have helped!

    • @coolguy284_2
      @coolguy284_2 Před 4 lety

      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.

  • @ronswanson69
    @ronswanson69 Před 6 lety +78

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

  • @startscratching6282
    @startscratching6282 Před 2 lety

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

  • @IMYTnNERDEE2
    @IMYTnNERDEE2 Před 6 lety

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

  • @yuehuang3419
    @yuehuang3419 Před 4 lety

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

  • @aidennymes6335
    @aidennymes6335 Před 6 lety

    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 Před 6 lety

      Just found out that archimedes did came up with that idea more than 2000 years ago

  • @abhishek.rathore
    @abhishek.rathore Před rokem

    We did this in a lab for our Concurrent and Parallel Programming class using multiple threads as it is easily parallelizable. Was fun.

  • @ethanhermsey
    @ethanhermsey Před 6 lety +5

    hahaha that rainbow unicorn hoodie :p

  • @FR12321
    @FR12321 Před 6 lety +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 Před 5 lety

      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

  • @SilaDrenja
    @SilaDrenja Před 2 lety +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 Před 2 lety +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 Před 2 lety

      @@Nilrem8 optimization gives me orgasm

  • @akinhwan
    @akinhwan Před 6 lety +3

    wow unicorn hoodie. game over

  • @mheermance
    @mheermance Před 4 měsíci

    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.

  • @trolololo720
    @trolololo720 Před 6 lety +20

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

    • @keejay98195
      @keejay98195 Před 4 lety +2

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

  • @TejasIsAmazing
    @TejasIsAmazing Před 2 lety

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

  • @flatearthasmr9034
    @flatearthasmr9034 Před 3 lety

    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

  • @VivekYadav-ds8oz
    @VivekYadav-ds8oz Před 5 lety

    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  Před 5 lety +1

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

  • @rysea9855
    @rysea9855 Před 4 lety +3

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

  • @Ciddyism
    @Ciddyism Před 6 lety

    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)

  • @alexalodu2247
    @alexalodu2247 Před 6 lety +4

    Omg I'm in love with his hoodie

  • @venkatbabu186
    @venkatbabu186 Před 4 lety

    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.

  • @empxrubix9387
    @empxrubix9387 Před 5 lety +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 Před 5 lety

      > 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 Před 5 lety

      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 Před 5 lety +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 Před 5 lety

      Zac K yea sorry, I'm not a native English speaker

    • @xnick_uy
      @xnick_uy Před 5 lety

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

  • @jacobhaig2372
    @jacobhaig2372 Před 6 lety +70

    Yay, its half TAU day!

    • @joostvanrens
      @joostvanrens Před 6 lety

      Jacob Haig no

    • @matheusd.rodrigues429
      @matheusd.rodrigues429 Před 6 lety +7

      Haha Tau day is a day after my birthday. That's a good approximation I think haha

    • @racheline_nya
      @racheline_nya Před 5 lety

      tau day. if the digits 6 and 8 swapped, it would be my nameday lol

    • @minijoe8059
      @minijoe8059 Před 5 lety

      Don't say that. Never say that. Don't even read it again. Pls No

  • @medo_shinwa3562
    @medo_shinwa3562 Před 4 lety +1

    I will believe any guy with a rainbow hoodie.

  • @DlcEnergy
    @DlcEnergy Před 3 lety

    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

  • @codercodercoder5977
    @codercodercoder5977 Před 3 lety

    teamlead from ibm told me this was an actual senior dev interview question cant remeber IBM or where but big bucks on the line.

  • @troyhayder6986
    @troyhayder6986 Před 3 lety

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

  • @sohansonu4u
    @sohansonu4u Před 4 lety

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

  • @alansmithee419
    @alansmithee419 Před 4 lety

    Fourteenth of march, 1592.
    What a day that was.

  • @michelbrasseur9296
    @michelbrasseur9296 Před 6 lety

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

  • @NarenSandy
    @NarenSandy Před 4 lety

    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.

  • @diconicabastion5790
    @diconicabastion5790 Před 2 lety

    Your biggest problem is the size of the circle and square. Increasing the size of them will increase precision.

  • @PRIMEVAL543
    @PRIMEVAL543 Před 4 lety +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)

  • @pixelgames3776
    @pixelgames3776 Před 6 lety +18

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

    • @anarcho.pacifist
      @anarcho.pacifist Před 6 lety +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 Před 6 lety

      I am curious for that one too, but i am unable to find it anywhere :(

    • @TheCodingTrain
      @TheCodingTrain  Před 6 lety +2

      https:/github.com/CodingTrain/PiDaygithub.com/CodingTrain/PiDay/github.com/CodingTrain/PiDay

    • @pixelgames3776
      @pixelgames3776 Před 6 lety

      Thank you!

    • @pixelgames3776
      @pixelgames3776 Před 6 lety

      The Coding Train but I can't seem to find the version that calculates number by number as you showed... There are other kinds.. :(

  • @stephencolbert934
    @stephencolbert934 Před 5 lety +3

    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 Před 4 lety

      Why the heck would you need pi in primary school?

  • @earthbjornnahkaimurrao9542

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

  • @GekoPoiss
    @GekoPoiss Před 5 lety

    It should be d

  • @dulata5934
    @dulata5934 Před 5 lety

    Try including the points on the circumference using

    • @SirRebrl
      @SirRebrl Před 4 lety

      Or just include them as half a point to start with, since that is the average between inclusion and exclusion.

  • @silviozanoli1574
    @silviozanoli1574 Před 6 lety

    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  Před 6 lety

      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 Před 6 lety

      I see your point, pretty good ! Thank you for the explanation

  • @RetroGamingClashOfClans

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

  • @ephraimtimmerman4476
    @ephraimtimmerman4476 Před 6 lety

    That circle is pretty God damn decent

  • @vtbn53
    @vtbn53 Před 3 lety

    Damn! For me this would be the greatest video channel ever IF you were coding in C++, sigh...

  • @TylerDunphy
    @TylerDunphy Před 6 lety +1

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

  • @kevnar
    @kevnar Před 3 lety +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 Před 3 lety

      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.

  • @jacobbianwilliam281
    @jacobbianwilliam281 Před 5 lety +1

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

  • @kamoroso94
    @kamoroso94 Před 6 lety +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.

  • @manasmahale5906
    @manasmahale5906 Před 6 lety

    I love your teaching sir

  • @thfreakinacage
    @thfreakinacage Před 6 lety

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

  • @charlesbenca5357
    @charlesbenca5357 Před 5 lety +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.

  • @kevnar
    @kevnar Před 2 lety

    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.

  • @dasamlan71
    @dasamlan71 Před 5 lety

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

  • @Alkis05
    @Alkis05 Před 3 lety

    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.

  • @josephguebara5967
    @josephguebara5967 Před 3 lety

    part 1 - WOW SIGNAL DECODED!
    part 2 - UFO discovered in PI, WOW SIGNAL DECODED!

  • @MKkniGEAR
    @MKkniGEAR Před 6 lety +1

    Doesn't make sense to use a more precise PI value to make sure you're close to PI, you never assume you know PI when you're calculating it :o

  • @hexagonist23
    @hexagonist23 Před 4 lety

    Rather than going to some sketchy website, you can compute 1 BILLION digits of pi in 5 minutes on your computer. Not a million, billion. Took me 5 minutes to compute with y-cruncher.

  • @Apofoo
    @Apofoo Před 6 lety +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 ?

    • @n_lisper
      @n_lisper Před 6 lety

      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 Před 6 lety

      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 Před 6 lety

      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 Před 6 lety

      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 Před 6 lety

      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.

  • @LucasAlfa.
    @LucasAlfa. Před 6 lety

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

  • @rianhasiando
    @rianhasiando Před 5 lety

    u made my day man

  • @neuralwarp
    @neuralwarp Před 3 lety

    Stop using (slow) random. Count all the pixels in a gigantic imaginary square. Use Bresenham's Circle Drawing Algorithm to calculate the changing radius of the circle as y increases, and count the number of pixels falling inside it. You only need to do it for a quarter square. Use a number-as-string library to do the division, once, or periodically. Maybe once a second using multi tasking with a sleep.

  • @superknife0512
    @superknife0512 Před 5 lety

    I know nothing about this programing language but still watch to the end :v

  • @leguminosa9
    @leguminosa9 Před 5 lety +1

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

  • @daydrim1694
    @daydrim1694 Před 5 lety +1

    I don’t think this method is ‘legal’ because Processing is probably using PI to draw the circle

    • @johnjelatis2033
      @johnjelatis2033 Před 5 lety

      Even if it uses PI to render the circle, remove the rendering and just leave it calculating distance - it still functions. You could also do it by hand to prove that, but you'd better have good random numbers over a lot of iterations...

  • @charliejulietdavies8715
    @charliejulietdavies8715 Před 5 lety +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

  • @DowzerWTP72
    @DowzerWTP72 Před 6 lety

    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

  • @Monkeyboy196five
    @Monkeyboy196five Před 5 lety +1

    Why not use 22 divided by 7 to calculate PI. Ive probably missed the point here so consider this a curious question. Maybe my memory from school is not serving me well but I remember being taught that 22 over 7 is another representation of PI.
    By the way, I like your channel. You have a good style. Thanks

    • @Monkeyboy196five
      @Monkeyboy196five Před 5 lety

      @@RampagingCoder When you say a few digits in, you mean before it starts repeating ?

    • @ffggddss
      @ffggddss Před 5 lety

      22/7 is greater than π by about 1 part in 2500 (22/7 - π = 0.001264489...)
      355/113 is greater than π by about 1 part in 12,000,000 (355/113 - π = 0.000000266764...)
      Fred

  • @GogiRegion
    @GogiRegion Před 6 lety +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 Před 4 lety

      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

  • @gldanoob3639
    @gldanoob3639 Před 6 lety +8

    Could you please provide the source code for the first pi calculator of the video??

    • @Thamios
      @Thamios Před 6 lety +1

      I've found an algorithm and wrote a JavaScript based on it :D!
      You can check it out here:
      codepen.io/Chris_Scomersi/pen/EEwmwp

    • @gldanoob3639
      @gldanoob3639 Před 6 lety +5

      I found it here!
      github.com/CodingTrain/PiDay/blob/master/PiCalc/PiCalc.pde

    • @Thamios
      @Thamios Před 6 lety +3

      Same method that I'm using :D I just wrote it in Javascript and added many features such as copying all digits with one click pausing and resuming auto scrolling to the bottom of the page and some colors for every digit :)

    • @TheCodingTrain
      @TheCodingTrain  Před 6 lety +2

      Great work!

    • @gldanoob3639
      @gldanoob3639 Před 6 lety +1

      Actually I saw you cloned the PiCalc file in your Pi Day video

  • @connerd745
    @connerd745 Před 6 lety +2

    Don't really understand coding but... Isn't it cheating to have a function that has the real value of Pi inside of your coding to compare to what you're getting? Kinda defeats the purpose and reasonings as to why one would need to create a programme to make Pi in the first place if this function exists

  • @Yarquen
    @Yarquen Před 6 lety

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

  • @gerardjensenolmos7862
    @gerardjensenolmos7862 Před 4 lety +2

    When you realize Processing uses pi to draw the circle

    • @azsamsiizbrah
      @azsamsiizbrah Před 4 lety +1

      Well he draws the circle only for visual purposes and he never uses it in the calculations

  • @DrUrlf
    @DrUrlf Před 3 lety +1

    You definitely need to wear that outfit with the hood up next time !

  • @lmaooxdd3899
    @lmaooxdd3899 Před 3 lety +1

    Can i use threading to speed it up?

  • @pyrokinetikrlz
    @pyrokinetikrlz Před 3 lety

    you better not open the "tau vs pi" can of worms! :D

  • @willemschipper7736
    @willemschipper7736 Před 5 lety

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

  • @RubyPiec
    @RubyPiec Před 4 lety

    console.log(Math.PI)
    Done!

  • @chromosoze
    @chromosoze Před 6 lety

    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