def ej2(): def f(x): return np.exp(-x) subint = [4, 10, 20] # Subintervalos a, b = 0, 1 res_integral, _ = integral(f, a, b) # Integral de f(x) res_trapecio = [] err_trapecio = [] res_pm = [] err_pm = [] res_simpson = [] err_simpson = [] i = 0 for s in subint: # Resultados de usar las reglas compuestas res_trapecio.append(intenumcomp(f, a, b, s, "trapecio")) res_pm.append(intenumcomp(f, a, b, s, "pm")) res_simpson.append(intenumcomp(f, a, b, s, "simpson")) # Error que se comete al usar las reglas compuesta err_trapecio.append(abs(res_integral - res_trapecio[i])) err_pm.append(abs(res_integral - res_pm[i])) err_simpson.append(abs(res_integral - res_simpson[i])) i = i + 1 print("Integral de f(x):", res_integral) print("Trapecio:", res_trapecio) print("Punto Medio:", res_pm) print("Simpson:", res_simpson) print("Errores absolutos del Trapecio:", err_trapecio) print("Errores absolutos del Punto Medio:", err_pm) print("Errores absolutos del Simpson:", err_simpson)
def pendulo(l, alfa): # Dado una longitud en metros y una amplitud alfa # devuelve el periodo de un pendulo alfa_rad = (alfa / 180) * pi # Transforma el alfa en radianes def f(x): return (1 - sin(alfa_rad/2)**2 * sin(x)**2)**(-1/2) i, _ = integral(f, 0, pi/2) g = 9.8 # 9.8 m/s² T = 4 * sqrt(np.divide(l, g)) * i return T
def ej5(): def fa(x): return np.exp(-x**2) def fb(x): return (x**2 * np.log(x + sqrt(x**2 + 1))) xa = np.arange(-10000, 10000) # Si usamos [-inf, inf] exedemos el limite xb = np.arange(0, 2) ya, yb = [], [] for ia in xa: ya.append(fa(ia)) for ib in xb: yb.append(fb(ib)) print("a) con Trapecio =", trapz(ya, xa)) print("a) con Simpson =", simps(ya, xa)) # Como no se pudo usar trapz y simps con intervalo infinito, usare quad print("a) con scipy.integrate.quad =", integral(fa, -np.inf, np.inf)[0]) print("b) con Trapecio =", trapz(yb, xb)) print("b) con Simpson =", simps(yb, xb)) # En este caso no hacia falta, pero es para que se note la diferencia print("b) con scipy.integrate.quad =", integral(fb, 0, 2)[0])
def ruin_estimated_prob(self, arm): #x = self.successes[arm] #y = self.pulls[arm]-self.successes[arm] #b = max(1.0, self.budget) return beta.cdf( 0.5, self.successes[arm] + 1, self.pulls[arm] - self.successes[arm] + 1) + integral( lambda p, x, y, b: ( (1 - p) / p)**b * beta.pdf(p, x + 1, y + 1), 0.5, 1.0, (self.successes[arm], self.pulls[arm] - self.successes[arm], max(1.0, self.budget)))[0]
def _cdf(self, x): '''The CDF of T = first interarrival time of a NHPP with rate function L(t) Args: ``x`` (``float``): A positive number Returns: F_T(x) = P(T <= x) ''' self.check_L() return 1 - exp(-integral(self.L, 0, x)[0])
def propensity_integral(self, state, time, delta_t): """Integrate propensity function from time to time+delta_t If the reaction is autonomous, this method returns self.propensity(state)*delta_t. If it is non-autonomous, the integral is calculated numerically. Override this method if the propensity function can be integrated analytically. (Requires scipy). """ if self.is_autonomous: return self.propensity(state) * delta_t elif delta_t == float('inf'): return float('inf') else: from scipy.integrate import quad as integral propensity = lambda t: self.propensity(state, t) return integral(propensity, time, time + delta_t)[0]
def matched_filter(strain,template,N_func,dt): ''' d is the windowed strain data A is the template N is the noise in FT space, m=conj(A)*d/N ''' # Window win=window(len(strain)) # Frequencies used df = 1/(dt*len(strain)) freq = np.fft.rfftfreq(len(strain),dt) N=N_func(freq) # FTs with window d_ft=np.fft.rfft(win*strain) A_ft=np.fft.rfft(win*template) # Matched filter mf_ft=np.conj(A_ft)*(d_ft/N) mf=np.fft.irfft(mf_ft) # Integrate to find halfway point intg = integral(np.abs(mf_ft), dx=df, initial=0) mid_idx = np.argmin(np.abs(intg - max(intg)/2)) sigsq_template = np.conj(A_ft)*A_ft/N # or is it np.conj(Aft)/(Aft*N) sigma = np.sqrt(np.abs(np.sum(sigsq_template)*df) ) sig_data = np.std(np.abs(mf)) max_data = np.max(np.abs(mf)) SNR_data = (max_data-np.mean(np.abs(mf)))/sig_data # Normalize to sigma=1 and shift back to zero SNR=np.fft.ifftshift(mf)/sigma return SNR, SNR_data, freq[mid_idx]
def calc_integral_scale(self): """Calculate the integral scale of the isotrope model.""" self._integral_scale = integral(self.correlation, 0, np.inf)[0] return self._integral_scale
def u_n(n): def f_n(t): return f(n, t) return integral(f_n, 0, np.inf)[0]
def F(x): def f_inf(t): return (1 - np.cos(x * t)) / (t**2 * (1 + t**2)) return integral(f_inf, 0, np.inf)[0]
def u_n(n): def f_n(t): return f(n, t) return integral(f_n, 0, np.inf)[0]
def F(x): def f_inf(t): return (1 - np.cos(x * t)) / (t**2 * (1 + t**2)) return integral(f_inf, 0, np.inf)[0]
def Mhalos(minM, maxM, z, P, box=True): from scipy.integrate import quad as integral return integral( MdndlnM, np.log(minM), np.log(maxM), args=(z, P, box, True))[0] * BoxSize**3
if (len(str(a)) == 3 and str(a)[2] == "0"): print(" Batas Bawah (a) : ", int(a)) else: print(" Batas Bawah (a) : ", a) if (len(str(b)) == 3 and str(b)[2] == "0"): print(" Batas Atas (b) : ", int(b)) else: print(" Batas Atas (b) : ", b) if (pil == "1"): print(" Jumlah Pias (n) : ", n) if (pil == "2"): print(" Interval (h) : ", h) print("\n\nNilai Integrasinya adalah : ", "%.6f" % integrasi) I = integral(f, a, b) result = I[0] - I[1] print("\n\n") if (len(str(b)) == 3 and str(b)[2] == "0"): print(int(b)) else: print(b) print(f"∫ {persUser} dx = {'%.4f'%I[0]} - {'%.4f'%I[1]}") if (len(str(a)) == 3 and str(a)[2] == "0"): print(int(a)) else: print(a, "\n\n") print("\nNilai Integrasi Sejatinya : ", "%.6f" % result, "\n\n\n") input("Ketik Enter untuk kembali ke menu ...")
def _pdf(self, x): self.check_L() return self.L(x) * exp(-integral(self.L, 0, x)[0])
z: float, m; axial location. z=0 is the midplane Returns: -------- q': float, kW/m; linear power at that location """ return Q1REF * exp(-ALPHA * (z / L + 0.5)) * cos(pi / L * z) print("A = {:.2f}, \t B = {:.1f}".format(A, B)) mdot = G * ACH print("mdot: {:.3f} kg/s".format(mdot)) xein = (hin - hf) / hfg print("Xe,in: {:.3f}".format(xein)) # Numerically solve for the onset of nucleate boiling f = lambda z: integral(q1, -L / 2, z)[0] / (mdot * hfg) + xein zonb = fsolve(f, 0.0)[0] print("zonb: {:.3f} m ({:.2f} m from inlet)".format(zonb, L / 2 + zonb)) # Finally, find the critical power ratio # Critical power is the point where the Hench-Gillis correlation for X_cr meets # the X_e curve. CPR is the factor times q1(z) necessary to make that occur. zrange = linspace(zonb, L / 2, NPOINTS) xcr_vals = array([hench_gillis(z - zonb) for z in zrange]) def _xe(cpr, z): _q1 = lambda _z: cpr * q1(_z) qdot = integral(_q1, zonb, z)[0] h = hf + 1.5E3 * qdot / (mdot * hfg) #print(h, h-hf, hf)
SPXe_data = loadtxt("xe_stopping_power_NIST.dat") SPXe_func = interpolate(SPXe_data[:,0],SPXe_data[:,1]*rho, kind="cubic") E = lambda p: ( p**2 + 0.511**2 )**0.5 P3 = lambda E: ( E**2 - 0.511**2 )**0.5 sigma = lambda p: 13.6*E(p)/p**2 * 0.01**0.5 * (1+0.038*log(0.01) ) for i in range(1): E0 = 2.5 + 0.511 xyzE = [Vector4(0.,0.,0.,0.)] u = Vector3(0.,0.,1.) while E0>0.511: p = P3(E0) dE = min(0.01, E0-0.511); E0 -= dE dS = integral( lambda e: 1.0/SPXe_func(e), E0,E0+dE, limit = 1000)[0] du = u * dS xyzE.append( Vector4(-dE,*(du+xyzE[-1][1]) ) ) sigmaMS = sigma(p) thetaX = _R.Gaus(0.,sigmaMS) thetaY = _R.Gaus(0.,sigmaMS) tanX = tan(thetaX) tanY = tan(thetaY) norm = sqrt(u[0]**2 + u[1]**2) M = Matrix( Vector(u[1],-u[0],0.)/norm, Vector(-u[0]*u[2],-u[1]*u[2],norm**2)/norm, u ).T() if norm else Identity(3) u = Vector3(* M ** Vector3( tanX, tanY, 1 ).Unit() ).Unit() E, xyz = zip(*xyzE); x, y, z = zip(*xyz) a = Plot4D(x,y,z,E)
def alpha(z): """Void fraction of the mixture on [0, L] Parameter: ---------- z: float, m; distance from the inlet at the bottom """ return two_phase.alpha(x(z), rhof, rhog) def rho(z): """Mixture density on [0, L] Parameter: ---------- z: float, m; distance from the inlet at the bottom """ return two_phase.mixture_density(rhof, rhog, alpha(z)) grav = lambda z: rho(z) * 9.81 dp_grav = integral(grav, 0, L)[0] print("\tDeltaP_grav: {:.2f} kPa".format(dp_grav / 1000)) fric = lambda z: fff / DH * G**2 / (2 * rho(z)) dp_fric = integral(fric, 0, L)[0] print("\tDeltaP_fric: {:.2f} kPa".format(dp_fric / 1000)) dp_accl = G**2 * (1 / rhom1 - 1 / rhof) print("\tDeltaP_accl: {:.2f} kPa".format(dp_accl / 1000)) dp_total = dp_grav + dp_fric + dp_accl print("\t -> DeltaP: {:.2f} kPa".format(-dp_total / 1000))
def _xe(cpr, z): _q1 = lambda _z: cpr * q1(_z) qdot = integral(_q1, zonb, z)[0] h = hf + 1.5E3 * qdot / (mdot * hfg) #print(h, h-hf, hf) return (h - hf) / hfg