def keyword(input): word={} keyword_manager=KeywordManager() total_len=0 input = input.replace("\r", "").split("\n") for i in input: i=i.strip().decode('utf-8') total_len+=len(i) for j in i: if j in stop_word: keyword_manager.sync() else: keyword_manager.add(j) keyword_manager.sync() word_list={} for k,v in keyword_manager.dict.iteritems(): if v.valid(): word_list[k]=float(int(v)) trash=set() def add(word): if word in word_list: if v/word_list[word]>0.618: trash.add(word) else: return False return True word_list_finally=[] for k,v in word_list.iteritems(): if len(k)>2: if add(k[1:]) and add(k[:-1]): if k not in trash: word_list_finally.append((k,v)) elif k not in trash: word_list_finally.append((k,v)) word_list2=[] no_login_word_list=[] from cmath import log10 for i in word_list_finally: if i[0].encode('utf-8') in dict_db: rank=log10(i[1]/float(dict_db[i[0].encode('utf-8')])).real word_list2.append( ( i[0], rank ) ) else: rank=i[1]*log10(len(i[0])).real if rank>1.7: no_login_word_list.append((i[0],rank)) sorter=lambda x,y:-1 if x[1]>y[1] else 0 if x[1]==y[1] else 1 word_list2.sort(sorter) no_login_word_list.sort(sorter) keyword_no=total_len/300+3 result=word_list2[:keyword_no]+no_login_word_list result.sort(sorter) return [i[0] for i in result]
def getVSMScore(index,nfiles,docName,QueryWords,VSM): score = 0 docName = str(docName) #分母的两个平方数 square1=0 square2=0 line=VSM[docName] #文档的平方数可以直接根据文件计算 for v in line.values(): square2+=float(v)**2 for word in QueryWords.keys(): if word not in index or docName not in index[word]: continue df = len(index[word]) #查询单词的Wf w_wf=1 + cmath.log10(QueryWords[word]).real idf = cmath.log10(nfiles / df).real weight_w=w_wf*idf weight_doc=float(line[word]) #分子 score +=weight_doc*weight_w score=adjust(word,score,docName) square1 +=(weight_w)**2 score=score/(cmath.sqrt(square2*square1).real) return score
def f(x): return (20 * cmath.log10( abs( cmath.cosh((complex( (math.sqrt(math.pi * x * mur * 4 * math.pi * math.pow( 10, -7) * sigma)) * math.cos(math.pi / 4), (math.sqrt(math.pi * x * mur * 4 * math.pi * math.pow( 10, -7) * sigma)) * math.sin(math.pi / 4))) * h)) ) + 20 * cmath.log10( abs(1 + 0.5 * ((complex(0, -k * x * radius)) / (complex( (math.sqrt(math.pi * x * mur * 4 * math.pi * math.pow( 10, -7) / sigma)) * math.cos(math.pi / 4), (math.sqrt(math.pi * x * mur * 4 * math.pi * math.pow( 10, -7) / sigma)) * math.sin(math.pi / 4))) + (complex( (math.sqrt(math.pi * x * mur * 4 * math.pi * math.pow( 10, -7) / sigma)) * math.cos(math.pi / 4), (math.sqrt(math.pi * x * mur * 4 * math.pi * math.pow( 10, -7) / sigma)) * math.sin(math.pi / 4))) / (complex(0, -k * x * radius))) * cmath.tanh((complex( (math.sqrt(math.pi * x * mur * 4 * math.pi * math.pow( 10, -7) * sigma)) * math.cos(math.pi / 4), (math.sqrt(math.pi * x * mur * 4 * math.pi * math.pow( 10, -7) * sigma)) * math.sin(math.pi / 4))) * h))) ).real
def get_wfidf(index, fileNum, docID, word): docID = str(docID) if docID not in index[word]: return "0" tf = len(index[word][docID]) df = len(index[word]) wf = 1 + cmath.log10(tf).real idf = cmath.log10(fileNum / df).real return wf * idf
def RoundSigFig(Z): s = 3 if (Z.real == 0): x = 0 else: x = round(Z.real, -(math.floor(log10(Z.real).real) - s)) if (Z.imag == 0): y = 0 else: y = round(Z.imag, -(math.floor(log10(Z.imag).real) - s)) return complex(x, y)
def get_wfidf_Score(index, fileNum, docID, wordList): score = 0 docID = str(docID) for word in wordList: if word not in index or docID not in index[word]: continue tf = len(index[word][docID]) df = len(index[word]) wf = 1 + cmath.log10(tf).real idf = cmath.log10(fileNum / df).real score += wf * idf return score
def F_Gmist_19con(G, d, A, x, e, Dl, Dv, ST): # G = 300 g = 9.81 # G=1; # G as fake input to weber and Froude, will be divided away. #Dimensionless Cross Sectional Area Occupied by Liquid Phase Ald = F_Ald_9(d, A, e) Avd = F_Avd_10(d, A, e) #Liquid Froude Number #Frl=F_FroudeLiquid_15( G,d,Dl ); #Liquid Weber Number for Flow Pattern #Wel=F_Weber_16_21( G,d,Dl,ST); Wel_Frl = g * d**2 * Dl / ST Fac = (1.138 + 2 * log10(pi / 1.5 / Ald))**(-2) Gmist = (7680 * (Avd**2) * g * d * Dl * Dv * (Wel_Frl)**(-1) / (x**2 * (pi**2) * Fac))**0.5 Gmist_org = Gmist # Find lowest point on curve xn = x dx = 0.01 dG = -1 while dG.real < 0: xn = xn - dx if xn < 0: xn = 0 en = F_Void_8(G, xn, Dl, Dv, ST) Aldn = F_Ald_9(d, A, en) Avdn = F_Avd_10(d, A, en) Facn = (1.138 + 2 * log10(pi / 1.5 / Aldn))**(-2) Gmist2 = (7680 * (Avdn**2) * g * d * Dl * Dv * (Wel_Frl)**(-1) / (xn**2 * (pi**2) * Facn))**0.5 dG = Gmist2 - Gmist if Gmist2.real < Gmist.real and x > 0.3: Gmist = Gmist2 #Gmist=Gmist_org; #--------evaporation---- # qcrit=F_CHF_23(Dl,Dv,Hl,Hv,ST); # Gdry=F_Gdry_19(q,d,x,Dl,Dv,Hl,Hv,ST); # #Transition Boundary - Dryout to Mist Flow (D-M) (Thome et al.) # Gmist=((1/0.502)*(log(0.61/x)+0.57)*(d/(Dv*ST))**(-0.16)*(1/(g*d*Dv*(Dl-Dv)))**(-0.15)*(Dv/Dl)**(0.09)*(q/qcrit)**(-0.72))**(1.613); # if Gmist<=Gdry # Gmist=Gdry; return Gmist
def happy_geek(GFT, c): v1 = 0 v2 = 0 for g in GFT: if (g.price == c.girl.bud) or (g.price - c.girl.bud <= 100) and ( c.boy.bud >= 0) and (c.boy.bud - g.price > 0): if (g.type == 'Luxury'): v2 = v2 + 2 * g.price else: v2 = v2 + g.price v1 = v1 + g.price c.GFT = c.GFT + [g] c.boy.bud = c.boy.bud - g.price for i in GFT: if (i not in c.GFT) and (i.type == 'luxury') and (i.price <= c.boy.bud): v2 = v2 + 2 * i.price v1 = v1 + i.price c.GFT = c.GFT + [i] c.boy.bud = c.boy.bud - i.price break if (c.girl.type == 'Choosy'): c.girl.happiness = log10(v2 if v2 > 0 else 1).real elif (c.girl.type == 'Normal'): c.girl.happiness = v1 else: c.girl.happiness = exp(v1).real c.boy.happiness = c.girl.intel c.set_happiness()
def createVSM(index, wordList, directname): # path = tools.projectpath + directname # path = os.path.join(tools.VSMpath,directname) if os.path.isdir(tools.reuterspath): files = os.listdir(tools.reuterspath) fileNum = len(files) VSM = {} for file in files: fileID = str(getDocID(file)) tf_idf_list = {} for word in wordList: tf_idf_list[word] = [] if fileID not in index[word]: tf_idf_list[word].append(0) continue #文章该词出现的频度,词频 tf = len(index[word][str(fileID)]) #出现该词的文章总数 df = len(index[word]) #保留三位小数,df/fileNum倒数 # idf = float("%.3f" % cmath.log(10 , fileNum / df).real) #逆向文本频率 idf = cmath.log10(fileNum / df).real #描述文章之间的相似性 tf_idf = "%.2f" % float(tf * idf) tf_idf_list[word].append(tf_idf) VSM[fileID] = tf_idf_list # print(tf_idf_list) VSMpath = os.path.join(tools.VSMpath, "VSM.json") tools.writeToFile(VSM, VSMpath)
def calcPloetner(self): """ Calculates the engine price from a regression applied to the Airliner Price Guide. The idiosyncratic error is neglected :Source: Influence of aircraft parameters on aircraft market price, K. Ploetner, M. Cole, M. Hornung, A. Isikveren, P. Wesseler, C. Essling, DLRK, 2012, table 3 """ desRange = self.parent.desRange.getValue() machCR = self.parent.machCR.getValue() paxSeats = self.parent.payload.paxSeats.getValue() vcabin = self.parent.fuselage.vcabin.getValue() sTOFL = self.parent.sTOFL.getValue() USDexchange = self.parent.USDexchangeEURO.getValue() # ======================================================================= # Constants # ======================================================================= a0 = 0.092 b = 0.000047 c = 0.207 d = 1.320 eR = 0.00023 f = 0.00018 Logprice = a0 + b * desRange / 1000.0 + c * machCR + d * log10(paxSeats) + eR * vcabin + f * sTOFL price = e ** Logprice * 1000000 * USDexchange return self.setValueCalc(price)
def dftplot(x, X, figtitle='Figure from DFTplot'): '''Plot a time domain signal and a frequency domain one''' N = len(X) Xreal = [0.0] * N Ximag = [0.0] * N Xamplitude = [0.0] * N Xdb = [0.0] * N Xphase = [0.0] * N for i in range(len(X)): Xreal[i] = X[i].real Ximag[i] = X[i].imag Xamplitude[i], Xphase[i] = cmath.polar(X[i]) if Xamplitude[i] != 0.0: Xdb[i] = 20 * cmath.log10(Xamplitude[i]) if Xamplitude[i] < 1e-10: Xphase[i] = 0.0 # Six axes, returned as a 2-d array f, axarr = plt.subplots(3, 2) f.suptitle(figtitle) axarr[0, 0].plot(x, 'go-') axarr[0, 0].set_title('Time domain samples') axarr[0, 1].plot(Xdb, 'go-') axarr[0, 1].set_title('Magnitude in db') axarr[1, 0].plot(Xreal, 'go-') axarr[1, 0].set_title('X[m] Real') axarr[1, 1].plot(Xamplitude, 'go-') axarr[1, 1].set_title('X[m] Amplitude') axarr[2, 0].plot(Ximag, 'go-') axarr[2, 0].set_title('X[m] Imaginary') axarr[2, 1].plot(Xphase, 'go-') axarr[2, 1].set_title('X[m] Phase') plt.show()
def goodTuringLinearReg(): print "Applying Good-Turing smoothing" bigrams = ngrams(tags, 2) freqBigrams = FreqDist(bigrams) for key in freqBigrams: if freqBigrams[key] not in Nc.keys(): Nc[freqBigrams[key]] = 1 else: Nc[freqBigrams[key]] += 1 '''####### Linear regression ####### ''' x = [np.real(log10(c)) for c in Nc.keys()] x = np.c_[np.ones_like(x), x] y = [np.real(log10(Nc[key])) for key in Nc.keys()] #print y linreg.fit(x, y)
def get_type_proect(self, lines): ''' Процедура по количеству строк кода определяет его крутость. Балл вычисляется по логарифмической шкале с десятичным основанием. ''' from cmath import log10 lines = str(abs(log10(lines))) lines = lines[:4] print 'Current ball: ', lines if lines[0] <= '1': return 'Nano project (level ' + lines[ 0] + ')<br>Total ball: ' + lines + '\n' elif lines[0] >= '1' and lines[0] <= '2': return 'Micro project (level ' + lines[ 0] + ')<br>Total ball: ' + lines + '\n' elif lines[0] >= '2' and lines[0] <= '3': return 'Mini project (level ' + lines[ 0] + ')<br>Total ball: ' + lines + '\n' elif lines[0] >= '3' and lines[0] <= '4': return 'Solid project (level ' + lines[ 0] + ')<br>Total ball: ' + lines + '\n' elif lines[0] >= '4' and lines[0] <= '5': return 'Big project (level ' + lines[ 0] + ')<br>Total ball: ' + lines + '\n' elif lines[0] >= '5' and lines[0] <= '6': return 'Whery big project (level ' + lines[ 0] + ')<br>Total ball: ' + lines + '\n' elif lines[0] >= '6' and lines[0] <= '7': return 'Multi project (level ' + lines[ 0] + ')<br>Total ball: ' + lines + '\n' elif lines[0] >= '7': return 'Global project (level' + lines[ 0] + ')<br>Total ball: ' + lines + '\n'
def getNc(c): #print c] x = [log10(c)] x = np.c_[np.ones_like(x), x] y_predict = linreg.predict(x) return pow(10, y_predict[0])
def happy_geek(GFT, c): v1 = 0 v2 = 0 for g in GFT: if (g.price == c.girl.bud) or (g.price-c.girl.bud <= 100) and (c.boy.bud >= 0) and (c.boy.bud - g.price > 0): if (g.type == 'Luxury'): v2 = v2 + 2*g.price else: v2 = v2 + g.price v1 = v1 + g.price c.GFT = c.GFT + [g] c.boy.bud = c.boy.bud - g.price logging.info('Gifting: Boy: ' + c.boy.name + ' gave his Girlfriend: ' + c.girl.name + ' Gift: ' + g.name + ' of price = ' + str(g.price) + ' rupees') for i in GFT: if (i not in c.GFT) and (i.type == 'luxury') and (i.price <= c.boy.bud): v2 = v2 + 2*i.price v1 = v1 + i.price c.GFT = c.GFT + [i] c.boy.bud = c.boy.bud - i.price logging.info('Gifting: Boy: ' + c.boy.name + ' gave his Girlfriend: ' + c.girl.name + ' Gift: ' + i.name + ' of price = ' + str(i.price) + ' rupees') break if (c.girl.type == 'Choosy'): c.girl.happiness = log10(v2 if v2 > 0 else 1).real elif (c.girl.type == 'Normal'): c.girl.happiness = v1 else: c.girl.happiness =exp(v1).real c.boy.happiness = c.girl.intel c.set_happiness() c.set_compatibility()
def dftplot(x,X): N=len(X) Xreal=[0.0]*N Ximag=[0.0]*N Xamp=[0.0]*N Xphase=[0.0]*N Xdb=[0,0]*N for i in range(len(X)): Xreal[i]=X[i].real Ximag[i]=X[i].imag Xamp[i],Xphase[i]=cmath.polar(X[i]) if Xamp[i]<1e-10: Xphase[i]=0 if Xamp[i] !=0.0: Xdb[i]=20*cmath.log10(Xamp[i]) f,axarr=plt.subplots(3,2) f.suptitle('figtitle') axarr[0,0].plot(x,'o-') axarr[0,1].plot(Xdb,'o-') axarr[1,0].plot(Xreal,'o-') axarr[2,0].plot(Ximag,'o-') axarr[1,1].plot(Xamp,'o-') axarr[2,1].plot(Xphase,'o-') plt.show
def happy_generous(GFT, c): v1 = 0 v2 = 0 for girl in GFT: if ((girl.price == c.boy.budget) or (c.boy.budget - girl.price <= 300)) and (c.boy.budget >= 0) and ( c.boy.budget - girl.price > 0): if (girl.type == 'Luxury'): v2 = v2 + 2 * girl.price else: v2 = v2 + girl.price v1 = v1 + girl.price c.GFT = c.GFT + [girl] c.boy.budget = c.boy.budget - girl.price info('Gifting: Boy: ' + c.boy.name + ' gave his Girlfriend: ' + c.girl.name + ' Gift: ' + girl.name + ' of price = ' + str(girl.price) + ' rupees') if (c.girl.type == 'Choosy'): c.girl.happiness = log10(v2 if v2 > 0 else 1).real elif (c.girl.type == 'Normal'): c.girl.happiness = v1 else: c.girl.happiness = exp(v1).real c.boy.happiness = c.girl.happiness c.set_happiness() c.set_compatibility()
def calcPloetner(self): ''' Calculates the engine price from a regression applied to the Airliner Price Guide. The idiosyncratic error is neglected :Source: Influence of aircraft parameters on aircraft market price, K. Ploetner, M. Cole, M. Hornung, A. Isikveren, P. Wesseler, C. Essling, DLRK, 2012, table 3 ''' desRange = self.parent.desRange.getValue() machCR = self.parent.machCR.getValue() paxSeats = self.parent.payload.paxSeats.getValue() vcabin = self.parent.fuselage.vcabin.getValue() sTOFL = self.parent.sTOFL.getValue() USDexchange = self.parent.USDexchangeEURO.getValue() #======================================================================= # Constants #======================================================================= a0 = 0.092 b = 0.000047 c = 0.207 d = 1.320 eR = 0.00023 f = 0.00018 Logprice = a0 + b * desRange / 1000. + c * machCR + d * log10( paxSeats) + eR * vcabin + f * sTOFL price = e**Logprice * 1000000 * USDexchange return self.setValueCalc(price)
def createVSM(index, wordList, directname): path = tools.projectpath + directname files = os.listdir(path) fileNum = len(files) VSM = {} for file in files: fileID = str(getDocID(file)) tf_idf_list = [] for word in wordList: if fileID not in index[word]: tf_idf_list.append(0) continue tf = len(index[word][str(fileID)]) df = len(index[word]) #保留三位小数 idf = cmath.log10(fileNum / df).real # idf = float("%.3f" % cmath.log(10 , fileNum / df).real) tf_idf = "%.2f" % float(tf * idf) tf_idf_list.append(tf_idf) VSM[fileID] = tf_idf_list # print(tf_idf_list) tools.writeToFile(VSM, tools.projectpath + 'VSM.json')
def log_func_complex(number, base = 10): try: if base == 10: return cmath.log10(number) return cmath.log(number, base) except (ValueError, TypeError, ZeroDivisionError): raise calculator.errors.EvaluationError('Cannot calculate logarithm of {} with base {}', number, base)
def multArgsFuncEval(function, arguments): # Evaluates functions with multiple parameters if function == "sum" or function == "mean": answer = 0 for arg in arguments: answer += arg if function == "sum": return answer return answer / len(arguments) elif function == "product": answer = 1 for arg in arguments: answer *= arg return answer elif function == "min": return min(arguments) elif function == "max": return max(arguments) elif function == "range": return max(arguments) - min(arguments) elif function == "median": return sorted(arguments)[len(arguments) / 2] elif function == "mode": return max(set(arguments), key = arguments.count) elif function == "variance" or function == "stdev": sum = 0 for arg in arguments: sum += arg mean = sum / len(arguments) answer = 0 for arg in arguments: answer += (arg - mean) ** 2 if function == "variance": return answer / len(arguments) return cmath.sqrt(answer / len(arguments)) elif function == "gcd": return gcd(arguments) elif function == "lcm": return lcm(arguments) elif function == "mod": firstNum = arguments[0] secondNum = arguments[1] return firstNum + (math.ceil((-firstNum / secondNum).real) + complex(0, 1) * math.ceil((-firstNum / secondNum).imag)) * secondNum elif function == "pow": answer = arguments[0] for i in xrange(1, len(arguments)): answer **= arguments[i] return answer elif function == "log": if len(arguments) == 1: return cmath.log10(arguements[0]) elif len(arguments) == 2: return cmath.log(arguments[0], arguements[1]) else: return "Error: 'log' has too many arguments." elif function == "rand": return random.uniform(arguments[0], arguments[1]) elif function == "randint": return random.randint(arguments[0], arguments[1])
def f(x): return 20 * cmath.log10( abs( cmath.sqrt(sigma * h * (complex(0, -k * x * radius))) * math.pow(3 * 10**8 / x / radius, 1 / 3) * math.pow( 1 - math.pi * l_max_otv * x / 3 / math.pow(10, 8), 6) * math.exp(2 * math.pi * r_prov / (s_grid - 2 * r_prov)))).real
def f(x): return 20 * cmath.log10( abs( cmath.sqrt(sigma * h * (complex(0, -k * x * radius))) * math.pow(3 * 10**8 / x / radius, 1 / 3) * math.pow(proverka_na_zero, 2) * math.pow( 1 - math.pi * l_max_otv * x / 3 / math.pow(10, 8), 6) * math.exp(2 * math.pi * h / l_max_otv))).real
def round_sigfigs(num, sig_figs=2): """Round to specified number of sigfigs. """ if num != 0: return round(num, -int(math.floor(math.log10(abs(num))) - (sig_figs - 1))) else: return 0 # Can't take the log of 0
def psnr(target, ref): import cv2 target_data = np.array(target, dtype=np.float64) ref_data = np.array(ref, dtype=np.float64) diff = ref_data - target_data diff = diff.flatten() rmse = cmath.sqrt(np.mean(diff**2.)) return 20 * cmath.log10(255 / rmse)
def ColebrookEquation(Dh, Ep, Re): Fd = 1e-3 aa = 1 while aa > 1e-5: bb = -2*log10(((Ep/Dh)/3.7)+2.51/(Re*Fd**0.5)) Fdprev = Fd; Fd = bb**(-2); aa = abs(Fd-Fdprev); return Fd
def F_hnb_8(p, q): #CO2 Critical Pressure pcrit = 73.773 #CO2 Molar Mass M = 44.0098 #Reduced Pressure pr = p / pcrit #Nucleate Boiling HTC hnb = 131 * pr**(-0.0063) * (-log10(pr))**(-0.55) * M**(-0.5) * q**(0.58) return hnb
def log(*args, **kw): arg0 = args[0] if isinstance(arg0, (int, float, long)): return _math.log10(*args,**kw) elif isinstance(arg0, complex): return _cmath.log10(*args,**kw) elif isinstance(arg0, _sympy.Basic): return _sympy.log10(*args,**kw) else: return _numpy.log10(*args,**kw)
def dBAmpspectrum(x: list, N: int): x = [i.real for i in x] threshold = max(x) / 10000 y = [] for n in range(N): if x[n].real < threshold: y.append(0.0) else: y.append(10 * log10(x[n].real).real) return y
def test_log10_cc (self): src_data = [complex(i,i+1) for i in range(-5, 5, 2)] expected_result = tuple(cmath.log10(i) for i in src_data) src = gr.vector_source_c(src_data) op = gr.transcendental('log10', 'complex_float') snk = gr.vector_sink_c() self.tb.connect(src, op, snk) self.tb.run() result = snk.data() self.assertComplexTuplesAlmostEqual(expected_result, result, places=5)
def createVSM(index, wordList): files = os.listdir(helper.rawpath) nfiles = len(files) VSM = {} for file in files: docName = str(helper.getFileName(file)) score = {} for word in wordList: if docName not in index[word]: continue tf = len(index[word][str(docName)]) wf = 1 + cmath.log10(tf).real df = len(index[word]) idf = cmath.log10(nfiles / df).real wf_idf = "%.2f" % float(wf * idf) score[word] = wf_idf VSM[docName] = score helper.Save(VSM, helper.datapath + 'vector.json')
def cylindrical_spreading_loss(self, dist): # dist in meters # http://www.dosits.org/science/advancedtopics/spreading/ # Sound cannot propagate uniformly # in all directions from a source in the ocean forever. # Beyond some range the sound will hit the sea surface or sea floor. # A simple approximation for spreading loss in a medium with upper and # lower boundaries can be obtained by assuming that the sound is distributed # uniformly over the surface of a cylinder having a radius equal to the range r # and a height H equal to the depth of the ocean return 10 * math.log10(dist) # decibels
def LOG10(df, price='Close'): """ Base-10 Logarithm """ log10_list = [] i = 0 while i < len(df[price]): log10 = cmath.log10(df[price][i]).real log10_list.append(log10) i += 1 return log10_list
def calculate_SSE(S): signal_len = len(S) SSE = np.zeros(signal_len) for tau_frame in range(0, signal_len): for t_frame in range(0, signal_len): k1 = (abs(S[tau_frame][t_frame]))**2 k2 = 0 if (k1 != 0): k2 = cmath.log10(k1) SSE[tau_frame] = SSE[tau_frame] + (k1 * k2) return SSE
def tfidf(index: dict, fileNum: int, tokens: list, doc: str): score = 0 for word in tokens: if word not in index.keys() or doc not in index[word]: continue tf = index[word][doc] df = len(index[word]) idf = cmath.log10(fileNum + 1 / df).real score += tf * idf return score
def check_palindrome_with_ints(num): exp = int(cmath.log10(num).real) while num > 9: last_digit = num % 10 tmp = (10**exp) first_digit = int(num / tmp) if first_digit != last_digit: return False exp -= 2 num -= tmp * first_digit num = int(num / 10) return True
def get_T(R): c1=[5.5582108,-6.41962,2.86239,-1.059453,0.328973,0.081621997,0.012647,0.00088100001,-0.001982,0.00099099998] c14=[43.140221,-38.004025,8.0877571,-0.913351,0.091504,-0.0036599999,-0.0060470002] c80=[177.56671,-126.69688,22.017452,-3.116698,0.59847897,-0.111213,0.01663,-0.0067889998] if R > 665.0: ww1 = c1 for i in range(0,len(c1)): ww1[i] = c1[i]*cmath.cos(i*cmath.acos(((cmath.log10(R)-2.77795312391)-(4.06801081354-cmath.log10(R)))/(4.06801081354-2.77795312391))) result = sum(ww1) elif R > 184.8: ww14 = c14 for i in range(0,len(c14)): ww14[i] = c14[i]* cmath.cos(i* cmath.acos(((cmath.log10(R)-2.22476915988)-(2.86208992852-cmath.log10(R)))/(2.86208992852-2.22476915988))) result = sum(ww14) else: ww80 = c80 for i in range(0,len(c80)): ww80[i]= c80[i]*cmath.cos(i*cmath.acos(((cmath.log10(R)-1.72528854694)-(2.3131455111-cmath.log10(R)))/(2.3131455111-1.72528854694))) result = sum(ww80) return Decimal(result.real).quantize(Decimal("0.00"))
def oneArgFuncEval(function, value): # Evaluates functions that take a complex number input if function == "sin": return cmath.sin(value) elif function == "cos": return cmath.cos(value) elif function == "tan": return cmath.tan(value) elif function == "asin": return cmath.asin(value) elif function == "acos": return cmath.acos(value) elif function == "atan": return cmath.atan(value) elif function == "csc": return 1.0 / cmath.sin(value) elif function == "sec": return 1.0 / cmath.cos(value) elif function == "cot": return 1.0 / cmath.tan(value) elif function == "ln": return cmath.log(value) elif function == "sqr": return cmath.sqrt(value) elif function == "abs": return cmath.sqrt((value.real ** 2) + (value.imag ** 2)) elif function == "exp": return cmath.exp(value) if function == "sinh": return cmath.sinh(value) elif function == "cosh": return cmath.cosh(value) elif function == "tanh": return cmath.tanh(value) elif function == "asinh": return cmath.asinh(value) elif function == "acosh": return cmath.acosh(value) elif function == "atanh": return cmath.atanh(value) elif function == "ceil": return math.ceil(value.real) + complex(0, 1) * math.ceil(value.imag) elif function == "floor": return math.floor(value.real) + complex(0, 1) * math.floor(value.imag) elif function == "trunc": return math.trunc(value.real) + complex(0, 1) * math.trunc(value.imag) elif function == "fac": if value.imag == 0 and value < 0 and value.real == int(value.real): return "Error: The factorial function is not defined on the negative integers." return gamma(value + 1) elif function == "log": return cmath.log10(value)
def log10(x): """ Return the base-10 logarithm of x. This is usually more accurate than ``log(x, 10)``. """ if isinstance(x,ADF): ad_funcs = list(map(to_auto_diff,[x])) x = ad_funcs[0].x ######################################## # Nominal value of the constructed ADF: f = log10(x) ######################################## variables = ad_funcs[0]._get_variables(ad_funcs) if not variables or isinstance(f, bool): return f ######################################## # Calculation of the derivatives with respect to the arguments # of f (ad_funcs): lc_wrt_args = [1/x/log(10)] qc_wrt_args = [-1./x**2/log(10)] cp_wrt_args = 0.0 ######################################## # Calculation of the derivative of f with respect to all the # variables (Variable) involved. lc_wrt_vars,qc_wrt_vars,cp_wrt_vars = _apply_chain_rule( ad_funcs,variables,lc_wrt_args,qc_wrt_args, cp_wrt_args) # The function now returns an ADF object: return ADF(f, lc_wrt_vars, qc_wrt_vars, cp_wrt_vars) else: # try: # pythonic: fails gracefully when x is not an array-like object # return [log10(xi) for xi in x] # except TypeError: if x.imag: return cmath.log10(x) else: return math.log10(x.real)
def calc(self): """ Calculates the turbulent friction coefficient k factor was chosen for smooth paint :Source: Aircraft Design: A Conceptual Approach, D. P. Raymer, AIAA Education Series, 1992, Second Edition, p. 282, Eq. 12.27-12.29 """ machCR = self.parent.aircraft.machCR.getValue() lfus = self.parent.lfus.getValue() Rcut1 = 38.21 * (lfus / 0.634e-5) ** 1.053 Rcut2 = 44.62 * (lfus / 0.634e-5) ** 1.053 * machCR ** 1.16 Re = self.parent.reynoldsNr.getValue() Reapp = min([Re, Rcut1, Rcut2]) return self.setValueCalc(0.455 / (log10(Reapp) ** 2.58 * (1 + 0.144 * machCR ** 2) ** 0.65))
def goo(event=None): line = edt.get() # vezmu celý uživatelský vstup items = line.split() # rozdělím ho na jednotlivé položky edt.delete(0,END) # vymažu vstupní pole for token in items: if token == '+': a = pop() b = pop() push(a+b) elif token == '*': a = pop() b = pop() push(a*b) elif token == '/': a = pop() b = pop() push(b/a) elif token == '-': a = pop() b = pop() push(b-a) elif token == 'log': a = pop() push(cmath.log10(a)) elif token == 'ln': a = pop() push(cmath.log(a)) elif token == 'pi': push(cmath.pi) elif token == 'e': push(cmath.e) else: if push(token): lblMsg.config(text="OK", fg='black') else: lblMsg.config(text="Chyba", fg='red') err = token + token.join( line.split(token)[1:] ) edt.delete(0,END) edt.insert(0,err) edt.icursor(0) edt.selection_from(0) edt.selection_to(len(token)) break
def spherical_spreading_loss(self, dist): # dist in meters # http://www.dosits.org/science/advancedtopics/spreading/ # Spherical spreading describes the decrease in level when a sound wave # propagates away from a source uniformly in all directions. return 20 * math.log10(dist) # decibels
def test_log10(self): self.assertAlmostEqual(complex(0.69897, 0.40272), cmath.log10(complex(3, 4)))
import math import cmath print("pi->", math.pi) print("e->", math.e) print("math.sin(30):", math.sin(30)) print("math.sin(60):", math.sin(60)) print("math.sqrt(9):", math.sqrt(9)) print("cmath.sqrt(-3):", cmath.sqrt(-3)) print("pow(3,2):", pow(3, 2)) print("math.log10(100):", math.log10(100)) print("math.log(100,math.e):", math.log(100, math.e)) print("cmath.log10(-100):", cmath.log10(-100)) print("abs(-1):", abs(-1)) print("fabs(-10):", math.fabs(-10)) print("math.ceil(4.1):", math.ceil(4.1)) print("math.floor(4.5):", math.floor(4.5)) print("round(2.142,2):", round(2.142, 2)) print("round(2.642,1):", round(2.642, 1)) x = [2, 12, 51, 23, 12612, 612, 3, 12, 2, 31] print("max(", repr(x), ")", max(x)) print("min(", repr(x), ")", min(x))
def passive_scan(self, sub, sonar): return [] logger.debug("--- Passive scan ---") logger.debug("Sub: {0}".format(sub)) logger.debug("Sonar: {0}".format(sonar)) sub_pos = sub.get_pos() assert isinstance(sub_pos, Point) result = {} # background_noise = self.get_background_noise() + sub.self_noise() #logger.debug("background_noise {0}".format(background_noise)) sub_self_noise = sub.get_self_noise() for idx, obj in self.objects.items(): obj_pos = obj.get_pos() obj_id = obj.get_id() # skips the sub itself if obj_id == sub.get_id(): continue range_in_knots = obj_pos.distance_to(sub_pos) # in knots/miles # if range > 15: # hard limit for object detection. # continue assert isinstance(obj.get_pos(), Point) s = obj.get_sound() # Source Level assert isinstance(s, Sound) logger.debug("** Examining: {i}: dist:{dist:5.2f} obj:{obj} type:{ty}".format(i=idx, dist=range_in_knots,\ obj=obj,\ ty=type(obj))) range_in_meters = knots_to_meters(range_in_knots) deep = sub.actual_deep ocean_deep = 2000.0 # in meters half_ocean_deep = ocean_deep / 2.0 if range_in_meters < half_ocean_deep: spreading_loss = self.spherical_spreading_loss(range_in_meters) else: # mix of spherical and cylindrical losses # spherical losses up to half_ocean_deep + cylindrical # http://www.dosits.org/science/advancedtopics/spreading/ # http://www.fas.org/man/dod-101/navy/docs/es310/SNR_PROP/snr_prop.htm spreading_loss = (10 * math.log10(range_in_meters)) + (10 * math.log10(half_ocean_deep)) ### transmission_loss ### def absorption_filter(freq, value): return value - self.sound_absortion_by_sea(freq, deep, temperature=self.temperature, salinity=self.salinity, pH=self.ph) * range_in_meters / 1000 s.filter(absorption_filter) def spreading_loss(freq, value): return value - spreading_loss s.filter(spreading_loss) sea_noise_level = self.background_noise_for_freq(freq) total_noise = sound.sum_of_decibels([sub_noise_level, sea_noise_level]) receiving_array_gain = sonar.array_gain(freq) # AG adicional_losses = 0 received_sound = source_level - transmission_loss \ + receiving_array_gain - adicional_losses stn = received_sound - total_noise # received_sound = self.calculate_dectect_frequences(sub, sonar, obj, obj_sound, range_in_knots) logger.debug("received sound: {0}".format(received_sound)) # total_received_sound = sum([i[1] for i in received_bands]) # total_received_noise = sum([i[2] for i in received_bands]) # signal_to_noise = total_received_sound - total_received_noise # logger.debug("total_received_sound : {0}".format(total_received_sound)) # logger.debug("total_received_noise : {0}".format(total_received_noise)) # logger.debug("signal_to_noise : {0}".format(signal_to_noise)) # logger.debug( # "* freq:{f} source level:{sl} deep:{deep}".format( # f=freq, deep=deep, # sl=source_level)) # logger.debug( # "spreading_loss:{spl} absorption:{at} sea_noise:{sean} sub_noise:{subn}".format( # at=absorption, # sean=sea_noise_level, # subn=sub_noise_level, # spl=spreading_loss)) # # logger.debug( # "receiving_array_gain:{gain} transmission_loss:{tl}".format( # gain=receiving_array_gain, # tl=transmission_loss)) # # logger.debug( # "total_noise:{tn} received_sound:{rs} stn:{stn}".format( # tn=total_noise, # rs=received_sound, # stn=stn)) # consolidate bands in a total detected signal-to-noise value total_detected_signal_to_noise = 0 detected_bands = {} for band in received_bands: freq = band[0] signal = band[1] noise = band[2] stn = signal - noise - sonar.detection_threshold # if stn > 0: # total_detected_signal_to_noise += stn # detected_bands[freq] = stn # logger.debug("total_detected_signal_to_noise : {0}".format(total_detected_signal_to_noise)) #if not isinstance(object_sound, Decibel): # received_sound = db(received_sound) # logger.debug("{i}: signal_to_noise:{stn}".format(i=i, stn=signal_to_noise)) if total_detected_signal_to_noise > 0: # error: greater the signal_to_noise, less the error if total_detected_signal_to_noise > 10 + sonar.detection_threshold: error = 0.0001 # means 0.1% in measure else: # the error moves from 5% to 1% in a exponencial decay error = 0.0001 + 0.0004 * math.exp(-0.5 * total_detected_signal_to_noise) # it's divided by 3 because in a gaussian 99% of time we are inside 3 sigmas... # so the error is "max" error for 99% of measures error /= 3 deep = obj.get_deep() # .add_noise(0.1*dist) bearing = sub_pos.bearing_to(obj_pos) #bearing = obj_pos.bearing_to(sub_pos) # Scan Result r = ScanResult(idx) r.signal_to_noise = total_detected_signal_to_noise # r.blades = 0 r.distance = range_in_knots * random.gauss(1, error) r.bearing = bearing * random.gauss(1, error) r.deep = deep * random.gauss(1, error) # r.bands = detected_bands logger.debug("scan_result: {0}".format(r)) # result.append(r) result[idx] = r logger.debug("--- END of passive scan ---") return result # def passive_scan(self, sub, sonar):
print('Rectangular Coordinates =', cmath.rect(modulus, phase)) # cmath constants print('π =', cmath.pi) print('e =', cmath.e) print('tau =', cmath.tau) print('Positive infinity =', cmath.inf) print('Positive Complex infinity =', cmath.infj) print('NaN =', cmath.nan) print('NaN Complex =', cmath.nanj) # power and log functions c = 2 + 2j print('e^c =', cmath.exp(c)) print('log2(c) =', cmath.log(c, 2)) print('log10(c) =', cmath.log10(c)) print('sqrt(c) =', cmath.sqrt(c)) # trigonometric functions c = 2 + 2j print('arc sine =', cmath.asin(c)) print('arc cosine =', cmath.acos(c)) print('arc tangent =', cmath.atan(c)) print('sine =', cmath.sin(c)) print('cosine =', cmath.cos(c)) print('tangent =', cmath.tan(c)) # hyperbolic functions c = 2 + 2j print('inverse hyperbolic sine =', cmath.asinh(c))
def apply(self, *operands): self.check_operands(*operands) return cmath.log10(operands[0])
def rpn_calc(input, angle_mode = 0): global stack single_arg_funcs = ['exp','sqrt','sin','asin','cos','acos','tan','atan', 'sinh','asinh','cosh','acosh','tanh', 'atanh','!', 'polar'] num, arg, option = parse(input) #print(num, arg, option) #print('\n') if arg == None and (num != None or num != 'Error'): config.stack.append(num) history.append('Entered number: ' + str(num) ) return config.stack # Simple arithmatic----------------------------------------------------------------------- if option == None and num != None: if arg not in single_arg_funcs: last = config.stack.pop() if arg == '+': try: result = Decimal(last) + Decimal(num) hist = str(last) + '+' + str(num) + '=' + str(result) except TypeError: result = last + num hist = str(last) + '+' + str(num) + '=' + str(result) if arg == '-': try: result = Decimal(last) - Decimal(num) hist = str(last) + '-' + str(num) + '=' + str(result) except TypeError: result = last - num hist = str(last) + '-' + str(num) + '=' + str(result) if arg == '*': try: result = Decimal(last) * Decimal(num) hist = str(last) + '*' + str(num) + '=' + str(result) except TypeError: result = last * num hist = str(last) + '*' + str(num) + '=' + str(result) if arg == '/': try: result = Decimal(last) / Decimal(num) hist = str(last) + '/' + str(num) + '=' + str(result) except TypeError: result = last / num hist = str(last) + '/' + str(num) + '=' + str(result) if arg == '**': try: result = pow(Decimal(last), Decimal(num) ) hist = str(last) + '**' + str(num) + '=' + str(result) except TypeError: result = last ** num hist = str(last) + '**' + str(num) + '=' + str(result) if arg == 'rt': try: result = root(Decimal(last), Decimal(num) ) hist = str(last) + 'raised to 1 over ' + str(num) + '=' + str(result) except TypeError: result = root(last + num) hist = str(last) + 'raised to 1 over ' + str(num) + '=' + str(result) if arg == '%': try: result = Decimal(last) % Decimal(num) hist = str(last) + '%' + str(num) + '=' + str(result) except TypeError: result = last % num hist = str(last) + '%' + str(num) + '=' + str(result) if arg == '!': try: result = Decimal(math.factorial(num)) hist = str(num) + '!' + '=' + str(result) except TypeError: result = math.factorial(num) hist = str(num) + '!' + '=' + str(result) if arg == 'exp': try: result = math.exp(Decimal(num)) hist = str(num) + 'exp' + '=' + str(result) except ValueError: result = cmath.exp(Decimal(num)) hist = str(num) + 'exp' + '=' + str(result) except TypeError: result = cmath.exp(num) hist = str(num) + 'exp' + '=' + str(result) if arg == 'sqrt': try: result = math.sqrt(Decimal(num)) hist = str(num) + 'sqrt' + '=' + str(result) except ValueError: result = cmath.sqrt(Decimal(num)) hist = str(num) + 'sqrt' + '=' + str(result) except TypeError: result = cmath.sqrt(num) hist = str(num) + 'sqrt' + '=' + str(result) if arg == 'log': try: result = math.log10(Decimal(num)) hist = str(num) + 'log10' + '=' + str(result) except ValueError: result = cmath.log10(Decimal(num)) hist = str(num) + 'log10' + '=' + str(result) except TypeError: result = cmath.log10(num) hist = str(num) + 'log10' + '=' + str(result) #================================= if arg == 'ln': try: result = math.log(Decimal(num)) hist = str(num) + 'ln' + '=' + str(result) except ValueError: result = cmath.log(Decimal(num)) hist = str(num) + 'ln' + '=' + str(result) except TypeError: result = cmath.log(num) hist = str(num) + 'ln' + '=' + str(result) #--------TRIG-------------------------------- if arg == 'sin': if angle_mode == 1: try: result = math.sin(Decimal(num)) hist = 'sin' + str(num) + '=' + str(result) except TypeError: result = cmath.sin(num) hist = 'sin' + str(num) + '=' + str(result) elif angle_mode == 0: try: result = math.sin(math.radians(Decimal(num))) hist = 'sin' + str(num) + '=' + str(result) except TypeError: result = cmath.sin(num) hist = 'sin' + str(num) + '=' + str(result) if arg == 'cos': if angle_mode == 1: try: result = math.cos(Decimal(num)) hist = 'cos' + str(num) + '=' + str(result) except TypeError: result = cmath.cos(num) hist = 'cos' + str(num) + '=' + str(result) elif angle_mode == 0: try: result = math.cos(math.radians(Decimal(num))) hist = 'cos' + str(num) + '=' + str(result) except TypeError: result = cmath.cos(num) hist = 'cos' + str(num) + '=' + str(result) if arg == 'tan': if angle_mode == 1: try: result = math.tan(Decimal(num)) hist = 'tan' + str(num) + '=' + str(result) except TypeError: result = cmath.tan(num) hist = 'tan' + str(num) + '=' + str(result) elif angle_mode == 0: try: result = math.tan(math.radians(Decimal(num))) hist = 'tan' + str(num) + '=' + str(result) except TypeError: result = cmath.tan(num) hist = 'tan' + str(num) + '=' + str(result) if arg == 'asin': if angle_mode == 1: try: result = math.asin(Decimal(num)) hist = 'asin' + str(num) + '=' + str(result) except TypeError: result = cmath.asin(num) hist = 'asin' + str(num) + '=' + str(result) elif angle_mode == 0: try: result = math.asin(math.radians(Decimal(num))) hist = 'asin' + str(num) + '=' + str(result) except TypeError: result = cmath.asin(num) hist = 'asin' + str(num) + '=' + str(result) if arg == 'acos': if angle_mode == 1: try: result = math.acos(Decimal(num)) hist = 'acos' + str(num) + '=' + str(result) except TypeError: result = cmath.acos(num) hist = 'acos' + str(num) + '=' + str(result) elif angle_mode == 0: try: result = math.acos(math.radians(Decimal(num))) hist = 'acos' + str(num) + '=' + str(result) except TypeError: result = cmath.acos(num) hist = 'acos' + str(num) + '=' + str(result) if arg == 'atan': if angle_mode == 1: try: result = math.atan(Decimal(num)) hist = 'atan' + str(num) + '=' + str(result) except TypeError: result = cmath.atan(num) hist = 'atan' + str(num) + '=' + str(result) elif angle_mode == 0: try: result = math.atan(math.radians(Decimal(num))) hist = 'atan' + str(num) + '=' + str(result) except TypeError: result = cmath.atan(num) hist = 'atan' + str(num) + '=' + str(result) if arg == 'sinh': try: result = math.sinh(Decimal(num)) hist = 'sinh' + str(num) + '=' + str(result) except TypeError: result = cmath.sinh(num) hist = 'sinh' + str(num) + '=' + str(result) if arg == 'cosh': try: result = math.cosh(Decimal(num)) hist = 'cosh' + str(num) + '=' + str(result) except TypeError: result = cmath.cosh(num) hist = 'cosh' + str(num) + '=' + str(result) if arg == 'tanh': try: result = math.tanh(Decimal(num)) hist = 'tanh' + str(num) + '=' + str(result) except TypeError: result = cmath.tanh(num) hist = 'tanh' + str(num) + '=' + str(result) if arg == 'asinh': try: result = math.asinh(Decimal(num)) hist = 'asinh' + str(num) + '=' + str(result) except TypeError: result = cmath.asinh(num) hist = 'asinh' + str(num) + '=' + str(result) if arg == 'acosh': try: result = math.acosh(Decimal(num)) hist = 'acosh' + str(num) + '=' + str(result) except TypeError: result = cmath.acosh(num) hist = 'acosh' + str(num) + '=' + str(result) if arg == 'atanh': try: result = math.atanh(Decimal(num)) hist = 'atanh' + str(num) + '=' + str(result) except TypeError: result = cmath.atanh(num) hist = 'atanh' + str(num) + '=' + str(result) if arg == 'rect': #continue here.... try: result = rect(last, num) hist = 'Convert ' + str(last) + ',' + str(num) + ' to rectangular coords.' except TypeError: result = 'Error' hist = 'Error in attempted conversion to rectangular coords. No result.' if arg == 'polar': try: result = polar(num) hist = 'Convert ' + str(num) + ' to polar coords.' except TypeError: result = 'Error' hist = 'Error in attempted conversion to polar coords. No result.' config.stack.append(result) history.append(hist) return config.stack #======================================================================================================================= #----Only argument passed----------------------------------------------------------------------------------------------- #======================================================================================================================= elif option == None and num == None: last = config.stack.pop() if arg not in single_arg_funcs: try: n_minus1 = config.stack.pop() except IndexError: try: config.stack.append(Decimal(last)) except TypeError: config.stack.append(last) except TypeError: config.stack.append(last) except Exception as e: return 'Error' if arg == '+': try: result = Decimal(n_minus1) + Decimal(last) hist = str(n_minus1) + '+' + str(last) + '=' + str(result) except TypeError: result = n_minus1 + last hist = str(n_minus1) + '+' + str(last) + '=' + str(result) if arg == '-': try: result = Decimal(n_minus1) - Decimal(last) hist = str(n_minus1) + '-' + str(last) + '=' + str(result) except TypeError: result = n_minus1 - last hist = str(n_minus1) + '-' + str(last) + '=' + str(result) if arg == '*': try: result = Decimal(n_minus1) * Decimal(last) hist = str(n_minus1) + '*' + str(last) + '=' + str(result) except TypeError: result = n_minus1 * last hist = str(n_minus1) + '*' + str(last) + '=' + str(result) if arg == '/': try: result = Decimal(n_minus1) / Decimal(last) hist = str(n_minus1) + '/' + str(last) + '=' + str(result) except TypeError: result = n_minus1 / last hist = str(n_minus1) + '/' + str(last) + '=' + str(result) if arg == '!': try: result = Decimal(math.factorial(last)) hist = str(last) + '!' '=' + str(result) except TypeError: result = math.factorial(last) hist = str(last) + '!' '=' + str(result) except OverflowError: config.stack.append(last) hist = str('Factorial overflow error, no result.') return 'Error' if arg == '**': try: result = pow(Decimal(last), Decimal(last)) hist = str(n_minus1) + '**' + str(last) + '=' + str(result) except TypeError: result = last ** last hist = str(n_minus1) + '**' + str(last) + '=' + str(result) if arg == 'log': try: result = math.log10(Decimal(last)) hist = str(last) +'log10' + '=' + str(result) except ValueError: result = cmath.log10(Decimal(last)) hist = str(last) +'log10' + '=' + str(result) except TypeError: result = cmath.log10(last) hist = str(last) +'log10' + '=' + str(result) if arg == 'ln': try: result = math.log(Decimal(last)) hist = str(last) +'ln' + '=' + str(result) except ValueError: result = cmath.log(Decimal(last)) hist = str(last) +'ln' + '=' + str(result) except TypeError: result = cmath.log(last) hist = str(last) +'ln' + '=' + str(result) if arg == 'rt': try: result = root(Decimal(last), Decimal(n_minus1)) hist = str(n_minus1) + 'root' + str(last) + '=' + str(result) except TypeError: result = root(last), (n_minus1) hist = str(n_minus1) + 'root' + str(last) + '=' + str(result) if arg == 'exp': try: result = math.exp(Decimal(last)) hist = str(last) +'exp' + '=' + str(result) except TypeError: result = cmath.exp(last) hist = str(last) +'exp' + '=' + str(result) if arg == 'sqrt': try: result = math.sqrt(Decimal(last)) hist = 'Square root of ' + str(last) + '=' + str(result) except ValueError: result = cmath.sqrt(Decimal(last)) hist = 'Square root of ' + str(last) + '=' + str(result) except TypeError: result = cmath.sqrt(last) hist = 'Square root of ' + str(last) + '=' + str(result) #----------Trig---------------------------------------- #--------TRIG-------------------------------- if arg == 'sin': if angle_mode == 1: try: result = math.sin(Decimal(last)) hist = 'sin' + str(last) + '=' + str(result) except TypeError: result = cmath.sin(last) hist = 'sin' + str(last) + '=' + str(result) elif angle_mode == 0: try: result = math.sin(math.radians(Decimal(last))) hist = 'sin' + str(last) + '=' + str(result) except TypeError: result = cmath.sin(last) hist = 'sin' + str(last) + '=' + str(result) if arg == 'cos': if angle_mode == 1: try: result = math.cos(Decimal(last)) hist = 'cos' + str(last) + '=' + str(result) except TypeError: result = cmath.cos(last) hist = 'cos' + str(last) + '=' + str(result) elif angle_mode == 0: try: result = math.cos(math.radians(Decimal(last))) hist = 'cos' + str(last) + '=' + str(result) except TypeError: result = cmath.cos(last) hist = 'cos' + str(last) + '=' + str(result) if arg == 'tan': if angle_mode == 1: try: result = math.tan(Decimal(last)) hist = 'tan' + str(last) + '=' + str(result) except TypeError: result = cmath.tan(last) hist = 'tan' + str(last) + '=' + str(result) elif angle_mode == 0: try: result = math.tan(math.radians(Decimal(last))) hist = 'tan' + str(last) + '=' + str(result) except TypeError: result = cmath.tan(last) hist = 'tan' + str(last) + '=' + str(result) if arg == 'asin': if angle_mode == 1: try: result = math.asin(Decimal(last)) hist = 'asin' + str(last) + '=' + str(result) except TypeError: result = cmath.asin(last) hist = 'asin' + str(last) + '=' + str(result) elif angle_mode == 0: try: result = math.asin(math.radians(Decimal(last))) hist = 'asin' + str(last) + '=' + str(result) except TypeError: result = cmath.asin(last) hist = 'asin' + str(last) + '=' + str(result) if arg == 'acos': if angle_mode == 1: try: result = math.acos(Decimal(last)) hist = 'acos' + str(last) + '=' + str(result) except TypeError: result = cmath.acos(last) hist = 'acos' + str(last) + '=' + str(result) elif angle_mode == 0: try: result = math.acos(math.radians(Decimal(last))) hist = 'acos' + str(last) + '=' + str(result) except TypeError: result = cmath.acos(last) hist = 'acos' + str(last) + '=' + str(result) if arg == 'atan': if angle_mode == 1: try: result = math.atan(Decimal(last)) hist = 'atan' + str(last) + '=' + str(result) except TypeError: result = cmath.atan(last) hist = 'atan' + str(last) + '=' + str(result) elif angle_mode == 0: try: result = math.atan(math.radians(Decimal(last))) hist = 'atan' + str(last) + '=' + str(result) except TypeError: result = cmath.atan(last) hist = 'atan' + str(last) + '=' + str(result) if arg == 'sinh': try: result = math.sinh(Decimal(last)) hist = 'sinh' + str(last) + '=' + str(result) except TypeError: result = math.sinh(last) hist = 'sinh' + str(last) + '=' + str(result) if arg == 'cosh': try: result = math.cosh(Decimal(last)) hist = 'cosh' + str(last) + '=' + str(result) except TypeError: result = math.cosh(last) hist = 'cosh' + str(last) + '=' + str(result) if arg == 'tanh': try: result = math.tanh(Decimal(last)) hist = 'tanh' + str(last) + '=' + str(result) except TypeError: result = math.tanh(last) hist = 'tanh' + str(last) + '=' + str(result) if arg == 'asinh': try: result = math.asinh(Decimal(last)) hist = 'asinh' + str(last) + '=' + str(result) except TypeError: result = math.asinh(last) hist = 'asinh' + str(last) + '=' + str(result) if arg == 'acosh': try: result = math.acosh(Decimal(last)) hist = 'acosh' + str(last) + '=' + str(result) except TypeError: result = math.acosh(last) hist = 'acosh' + str(last) + '=' + str(result) if arg == 'atanh': try: result = math.atanh(Decimal(last)) hist = 'atanh' + str(last) + '=' + str(result) except TypeError: result = math.atanh(last) hist = 'atanh' + str(last) + '=' + str(result) if arg == 'rect': #continue here.... try: result = rect(n_minus1, last) hist = 'Convert ' + str(n_minus1) + ',' + str(last) + ' to rectangular coords.' except TypeError: result = 'Error' hist = 'Error in attempted conversion to rectangular coords. No result.' if arg == 'polar': try: result = polar(last) hist = 'Convert complex value ' + str(last) + ' to rectangular coords.' except TypeError: result = 'Error' hist = 'Error in attempted conversion to polar coords. No result.' config.stack.append(result) history.append(hist) return config.stack
def IMLOG10(z): c = im(z) return cmath.log10(c)
assert abs(exp1() - math.e) < 1e-14 assert abs(exp(x) - math.exp(x)) < 1e-14 assert abs(exp(log(x)) - x) < 1e-14 #------------------------------------------------------------------------------ # Exponential and log functions - complex version x = complex(-1) assert abs(sqrt(x) - cmath.sqrt(x)) < 1e-14 x = complex(0,0.5) assert abs(log(x) - cmath.log(x)) < 1e-14 assert abs(log10(x) - cmath.log10(x)) < 1e-14 assert abs(log(x,2) - cmath.log(x)/cmath.log(2)) < 1e-14 assert abs(exp(x) - cmath.exp(x)) < 1e-14 assert abs(exp(log(x)) - x) < 1e-14 #------------------------------------------------------------------------------ # Hyperbolic functions - real version x = 0.5 assert abs(cosh(x) - math.cosh(x)) < 1e-14 assert abs(sinh(x) - math.sinh(x)) < 1e-14 assert abs(tanh(x) - math.tanh(x)) < 1e-14 #------------------------------------------------------------------------------
def test_log10(): assert isnear(cmath.log10(0.1), log10(0.1)) assert isnear(cmath.log10(1), log10(1)) assert isnear(cmath.log10(123.45), log10(123.45))
def log10(a, b): result = a**2 + b**2 return cmath.log10(result) + 1.6j
def distanceMedoid(tweetAttributeFileName, medoidFileName, distanceFileName): print("Counting distance from medoids using %s %s %s" % (tweetAttributeFileName,medoidFileName, distanceFileName) ) previousDistances = [] # read existing distances try: distanceFile = open(distanceFileName, 'r') for line in distanceFile: previousDistances.append(line.replace('\n', '')) distanceFile.close() except IOError: print( "%s no previous data" % distanceFileName ) distanceFile = open(distanceFileName, 'w') tweetAttributeFile = open(tweetAttributeFileName, 'r') medoidFile = open(medoidFileName, 'r') attributesLine = medoidFile.readline() # ignore attributes names # read medoids to 2d array : groups/attributes groupCollection = [] groupIdx = 0 for line in medoidFile: #skip row name line = line.split(' ', 1)[1] #split attributes featureCollection = line.split(' ') medoidCollection = ndarray((len(featureCollection),1),float) # get medoid of each attribute to column. each row is a group for attributeIdx in range(0, len(featureCollection)): medoidCollection[attributeIdx] = float(' '.join(featureCollection[attributeIdx].split())) groupIdx += 1 groupCollection.append(medoidCollection) #print(groupCollection) # count distances to medoids lineIdx = 0 maxDist = 0.0 minDist = float('inf') currentDistances = [] for line in tweetAttributeFile: #skip row name line = line.split(' ', 1)[1] #split attributes featureCollection = line.split(' ') attributes = ndarray((len(featureCollection),1),float) # calc distance of each attribute of a row (sample tweet) from each medoid column for attributeIdx in range(0, len(featureCollection)): attributes[attributeIdx] = float(' '.join(featureCollection[attributeIdx].split())) # calc distance from given point to each medoid distanceVec = ndarray((len(groupCollection),len(featureCollection)),float) for i in range(0, len(groupCollection)): distanceVec[i] = np.linalg.norm(attributes-groupCollection[i]) #print(distanceVec) distance = 0.0 # TODO here we try to not have circles around a europs medoid. instead try to break it for i in range(0, len(distanceVec)): for j in range(0, len(attributes)): multitude = 1 #+ 2*j if (j % 2 == 0) and (attributes[j] > groupCollection[i][j]): multitude += 3 #* (attributes[j] - groupCollection[i][j]) if (j % 2 == 1) and (attributes[j] <= groupCollection[i][j]): multitude += 3 #* (groupCollection[i][j]-attributes[j]) #multitude = 1 # this line makes the groups circular again distance += float(multitude)*log10(distanceVec[i][j]+1) # need to move from zero a bit for log real = float(0) if isinstance(distance, complex) and distance.imag != 0: print ("Distance: (%s) is complex at line %d (%d,%d)"%(distance, lineIdx, i, j)) raise TypeError() elif isinstance(distance, complex) and distance.imag == 0: real = distance.real currentDistances.append(real) else: real = distance currentDistances.append(distance) #gathering min and max to use for normalization if real > maxDist: maxDist = real if real < minDist: minDist = real lineIdx += 1 lineIdx = 0 print "previousDistances len is %d" % len(previousDistances) print "currentDistances len is %d" % len(currentDistances) prevDistLen = len(previousDistances) for distance in currentDistances: #every written distance will be normalized if prevDistLen == 0: # need to have a first column with no data distanceFile.write("nothing " + str((distance*32 - minDist*32)/maxDist)+"\n") else: if prevDistLen <= lineIdx: print "line index is %d "%lineIdx raise IndexError() distanceFile.write(previousDistances[lineIdx] + " " + str((distance*32 - minDist*32)/maxDist)+"\n") lineIdx += 1 tweetAttributeFile.close() medoidFile.close() distanceFile.close()
def log10_usecase(x): return cmath.log10(x)
def get_log_probability(self, word): return cmath.log10(self.get_probability(word))