Created
June 1, 2022 11:05
-
-
Save ScratchyCode/38084967f913dfcd4328e977e3816964 to your computer and use it in GitHub Desktop.
Stima la costante di Nepero generando numeri casuali
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
MIN = 0 | |
MAX = 1 | |
#lanci = int(input("Numero di lanci: ")) | |
lanci = 10000000 | |
if(lanci <= 0): | |
print("Uscita...") | |
quit() | |
uscite = [] | |
for i in range(lanci): | |
somma = 0 | |
j = 0 | |
while(somma < MAX): | |
somma += random.uniform(MIN,MAX) | |
j += 1 # numero di lanci | |
uscite.append(j) | |
media = sum(uscite) / len(uscite) | |
print("e ~= %f" %media) | |
print("Err: %f" %(media - 2.71828182845904523536)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import threading | |
# parametri elaborazione | |
MIN = 0 | |
MAX = 1 | |
def nepero(lanci,risultati,index): | |
n = 0 | |
count = 0 | |
for i in range(lanci): | |
somma = 0 | |
while(somma < MAX): | |
somma += random.uniform(MIN,MAX) | |
count += 1 # conto quante volte sommo | |
n += 1 # conto quanti count ho avuto | |
media = count/n | |
risultati[index] = media | |
return | |
if(__name__ == "__main__"): | |
numthread = 4 | |
#lanci = int(input("Numero di lanci: ")) | |
lanci = 10000000 | |
if(lanci <= 0): | |
print("Uscita...") | |
quit() | |
# inizializzo le liste di thread e relativi risultati | |
threads = [None] * numthread | |
risultati = [None] * numthread | |
# avvio i thread | |
for i in range(numthread): | |
threads[i] = threading.Thread(target=nepero,args=(int(lanci/numthread),risultati,i)) | |
threads[i].daemon = True | |
threads[i].start() | |
# aspetto che finiscano le elaborazioni | |
for i in range(numthread): | |
threads[i].join() | |
# metto insieme tutti i risultati facendo la media delle medie | |
media = sum(risultati)/len(risultati) | |
print("e ~= %f" %media) | |
print("Err: %f" %(media - 2.71828182845904523536)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment