Approximating Euler's number using randomly generated integers

2 views (last 30 days)
This is for a problem I've been trying to solve and am stuck on one part of it.
Someone else has posted a question on how to solve this same problem but I am trying to solve it in a different way.
Start by generating K uniform random integers between 1 and K. Compute J, the number of integers between 1 and K, which were never generated. We then approximate the e by the ratio
K/J
Eg. K=5 Assume the following integers are randomly generated between 1 and 5.
1 1 2 3 2
Integers 1 2 3 4 5
Number of Instances 2 2 1 0 0
Two integers were never generated (4 and 5) so J =2
Consequently e is approximated by
5/2 = 2.5
Write a function called eapprox that takes the value of K as input, and which then approximates e using the method above. Test your function several times with different values of K. and compare the result to the value of e calculated using the built-in MATLAB function.
So far I have been able to generate the list of random integers using:
k = input('Enter value for k')
x = randi([1,k],1,k)
I am wondering how I can get matlab to go through the random list of integers and find which values were not generated and how many. I suppose it doesn't matter which integers weren't generated, just how many.
I have looked through the basics of indexing available through the help menu in matlab and nothing seems to be relevant to this problem.
Any help would be greatly appreciated.

Accepted Answer

James Tursa
James Tursa on 1 Apr 2015
Edited: James Tursa on 1 Apr 2015
Consider this: Since you have K numbers from 1 to K, for every duplicate number that means another number in the sequence was not generated. So counting duplicates is the same as counting missing numbers. Then consider what you get when you apply the following two function to your random integer vector:
sort % apply this function first
diff % then apply this function to the result of sort
Look at a small example of these results and I think you will be able to come up with an algorithm.
Or if you can't get it with that, then consider using the following function instead:
unique
Again, look at a small example and see if you can come up with an algorithm based on the result.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!