Advertisement
Guest User

C++ vs Matlab Script for 493 - UNDER THE RAINBOW

a guest
Mar 15th, 2017
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. void solve()
  2. {
  3. mpz_class EXPECTATION = 0;
  4. mpz_class sum = 0;
  5. for(int i = 2; i <= 7; i++) //Contains the number of balls at each "color #". ie, when i == 2,
  6. //We calculate the probability/expectation for 2 distinct colors
  7. {
  8. mpz_class f1;
  9. mpz_class f2, numerator;
  10. numerator = nCr(f1, 9*i, 20-i) * nCr(f2, 7, i); // ( 7 C n )* ( 9*n C 20-n )
  11. cout << "NUMERATOR = " << numerator.get_str() << "\t\t";
  12. EXPECTATION += (i * numerator); // E(X) = x_i * P(x_i)
  13. sum += numerator;
  14. cout << "Done with ... " << i << "\t SUM = " << sum.get_str() << endl;
  15. cout << "EXPECTATION IS " << EXPECTATION.get_str()<< endl << endl;
  16.  
  17. }
  18. mpf_t num, denom;
  19. mp_exp_t exponent;
  20.  
  21. //C++ Formatting Black Magic
  22. mpf_init(num); mpf_init(denom);
  23. mpf_set_str(num, EXPECTATION.get_str().c_str(), 10);
  24. mpf_set_str(denom, sum.get_str().c_str(), 10);
  25. size_t digits = 20;
  26. cout << "NUM = " << mpf_get_str(NULL, &exponent, 10, digits, num) << endl;
  27. cout << "DENOM = " << mpf_get_str(NULL, &exponent, 10, digits, denom) << endl;
  28.  
  29. mpf_t result;
  30. mpf_init(result);
  31. mpf_div(result, num, denom);
  32. mpf_class t (result);
  33. //Printing result
  34. cout << "RESULT IS " << t.get_str(exponent, 10, 0) << endl;
  35. }
  36. //In this case, the "Result" is about 6.055 (which is the wrong answer. I checked by plugging in and getting an intimidating red X mark indicating my folly)
  37.  
  38. //Compare to this matlab script
  39. %Project Euler - 493 (UNDER THE RAINBOW)
  40. %Given 70 balls in an urn (10 for each of the seven folors in the rainbow)
  41. %What is the expected number of distinct colors in 20 randomly picked
  42. %balls?
  43.  
  44. %Because this is a monte carlo simulation, it doesnt give an exact answer
  45. %Only a really really good approximation (about 6.382)
  46. clear
  47. close
  48. NUM_TRIALS = 100000
  49. recurringCount = 0
  50. for N = 1:NUM_TRIALS
  51. URN(1:1, 1:7)= 10;
  52. Size_Urn = sum(URN);
  53. for trial = 1:20 %20 trials
  54. randNum = rand() * Size_Urn +10;
  55. color = (floor(randNum/10));
  56. URN(color) = URN(color) - 1;
  57. Size_Urn = Size_Urn -1;
  58. end
  59.  
  60. distinct_Colors = 0;
  61. for urnInd = 1:7
  62. if(URN(urnInd) ~= 10)
  63. distinct_Colors = distinct_Colors + 1;
  64. end
  65. end
  66. recurringCount = recurringCount + distinct_Colors;
  67. end
  68.  
  69. format long
  70. recurringCount / NUM_TRIALS
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement