Hello everyone I tried implementing a custom random function I have worked on as a challenge. The program down below is a simple Pi finder that works well with the normal "random" library. I made some functions to try to achieve randomness with the use of the time module. It's random enough that I can say it works.
The problem I'm having is:
while counter<sayı:
x = 2*random.random()-1 #a random long float
y = 2*random.random()-1
When I substitute the random.random() by my randrand() function, the shell does not give anything back. I am really thinking that I'm messing up with the while loop, as I somehow make it an infinite loop. Here is what I'm trying to turn it into:
while counter<sayı:
x = 2*randrand()-1
y = 2*randrand()-1
Here are some things you should know:
- Yes, there are easier alternatives.
- Yes, I am a beginner so don't go too hard on me.
-
If there is an error with another part a solution to that would also be highly appreciated. (Don't think there are any as I tried debugging it quite a bit.)
PS:Please disregard the comments as they are written in Turkish.
Here is the full file.
Pi finder
import time
import struct #bu yeni öğrendiğim bir sey
def rand(x):
if x <= 0:
return "Number should be above 0!"
bLength = x.bit_length()
a = randombits(bLength)
while a >= x:
a = randombits(bLength) #eger a x'ten buyukse buyuk olmayana kadar devam ediyor.
return a
def lastbit(f):
return struct.pack('!f', f)[-1] & 1 #bunu direk ctrl+c ctrl+v yaptım.
def randombits(x):
r = 0
for _ in range(x): #Bunu arka arkaya ayni sayi cikartmamak icin koydum.
r <<= 1
#tum bitleri bir yana kaydiriyor.
#0111 olan 7 sayısı 1110 olan 14 sayısı oluyor orneğin.
#sırf iki ile çarpmak işe yararmis gibi dursa da,
#r = 0 iken bitleri bir yana kaydirmanin nedenini dusunuyorum.
r |= lastbit(time.clock()) #bu yeni oğrendigim struct kullanan bir func.
time.sleep (0.002)
return r
def randint(a, b): #bu kısım daha kolaydi.
x = a + rand(b-a+1)
if x > b:
randint(a,b) #alin hocam size recursive function. bence ben ap cs'e atlarim. xD
return x
def randrand(): #bu yaptigim akillica degilse ne
gg = "0."
for i in range(12):
a = randint(10,99)
gg += str(a)
return float(gg)
import random
sayı = randint(50,500) #Bu sayı ne kadar artarsa Pi sayısına o kadar yaklaşıyor.
pInCircle = float(0)
counter=0
while counter<sayı:
x = 2*random.random()-1 #rastgele uzun bir float
y = 2*random.random()-1 #tıpkısının aynısı
if x**2 + y**2 < 1: #direk küçüktür koydum çünkü o iki sayının
pInCircle +=1 #toplamının 1 olma ihtimali virtually sıfır
counter+=1
print (random.random()) #debug & testing
print (randrand()) #debug & testing
print (randrand()-1) #debug & testing
print ("Pi'nin değeri = " + str((4 * pInCircle/sayı)) + " (" + str(sayı) + " kere denendi.)")
Aucun commentaire:
Enregistrer un commentaire