コード例 #1
0
ファイル: unary_ops.py プロジェクト: psg-mit/fast_reals
def interval_sqrt(interval, context_down, context_up):
    lower, upper = interval
    sqrt_down, sqrt_up = bf.sqrt(lower,
                                 context_down), bf.sqrt(upper, context_up)
    out_interval = [sqrt_down, sqrt_up]
    derivs = [1 / (2 * sqrt_down), 0], [0, 1 / (2 * sqrt_up)]
    return out_interval, derivs
コード例 #2
0
ファイル: rsa.py プロジェクト: alexkiro/python-crypto
    def generate_keys(self,weak):
        ok=0
        nr=0
        print "Generating p"
        while ok==0:
            self.p=randrange(pow(2,self.bits),pow(2,self.bits+1),2)+1   ##random odd number
            ok=self.miller_rabin(self.p,10)                             ##check primality
            nr+=1                                                       ##number of tries 
        ok=0
        print "\t",nr,"tries"
        print "Generating q"
        nr=0
        if 2*self.p>pow(2,self.bits+1):             ## p<q<2p
            limit=pow(2,self.bits+1)
        else:
            limit=2*self.p
        while ok==0:
            self.q=randrange(pow(2,self.bits),limit,2)+1
            ok=self.miller_rabin(self.q,10)
            nr+=1
        print "\t",nr,"tries"
        self.n=self.p*self.q
        euler=(self.p-1)*(self.q-1) 

        print "Generating private key"
        
        if (weak==0):
            print "\t[Weak mode OFF]"
            self.e=65537
            x=self.eea(self.e,euler)
            self.d=x[0]%euler
        else:
            print "\t[Weak mode ON]"
            ok=0
            nr=0
            t=long(bigfloat.sqrt(bigfloat.sqrt(self.n))/3)
            while ok==0:
                self.d=randrange(2,t,2)-1
                ok=self.miller_rabin(self.d,10)
                nr+=1
            print "\t",nr,"tryes"
            x=self.eea(self.d,euler)
            self.e=x[0]%euler
            
        ##print self.e*self.d%euler
        ##print fractions.gcd(self.e,self.d)
        ##print self.d<long(bigfloat.sqrt(bigfloat.sqrt(self.n))/3)
                
        print "Done"
コード例 #3
0
def calcRayLengthsAndFarFieldDiff(refRayAngles, cellOffsetToRefRay, sim,
                                  detector):
    """Calculates the distance of a ref ray with given angles (y,z) (towards smaller idxs) to the detector,
       the distance of a 2nd ray with a given offset in sim cells (y,z) going to the same point
       and the difference between those 2 using the far field approximation
       Return tuple (lRefLen, lRayLen, lApproxDiff)
    """
    assert (len(refRayAngles) == 2)
    assert (len(cellOffsetToRefRay) == 2)
    # Convert to meters
    rayOffset = cellOffsetToRefRay * sim.cellSize[1:]
    dydzRef = np.array([bf.tan(refRayAngles[0]),
                        bf.tan(refRayAngles[1])]) * detector.distance
    lRef = bf.sqrt(detector.distance**2 + dydzRef[0]**2 + dydzRef[1]**2)
    dydzRay = dydzRef + rayOffset
    lRay = bf.sqrt(detector.distance**2 + dydzRay[0]**2 + dydzRay[1]**2)
    # Projection of rayOffset-Vector (with x=0) on lRay
    lDiff = np.dot(dydzRay, rayOffset) / lRay
    return (lRef, lRay, lDiff)
コード例 #4
0
ファイル: pb80.py プロジェクト: oursinblanc/Euler
def main():
    start = time.perf_counter()
    somme = 0

    for i in range(1, 101):
        rac = bigfloat.sqrt(i, bigfloat.precision(385))
        if rac != int(rac):
            s = partie_decimale(rac)[:100]
            somme += sumdigits(int(s))

    print(somme)
    print('temps d execution', time.perf_counter() - start, 'sec')
コード例 #5
0
def calcPhase(particle, detector, sim, waveLen):
    """Calculate the phase the particle has at the detector (current phase assumed to be 0)"""
    detCellIdx = getBinnedDetCellIdx(particle, detector, sim)
    #print("Target angles:", (detCellIdx - detector.size / 2) * detector.anglePerCell)
    dx = detector.distance + (sim.size[0] - particle.pos[0]) * sim.cellSize[0]
    dzdy = (detCellIdx - detector.size / 2) * detector.cellSize
    dydz = np.flipud(dzdy) + (sim.size[1:] / 2 -
                              particle.pos[1:]) * sim.cellSize[1:]
    distance = bf.sqrt(dx**2 + dydz[0]**2 + dydz[1]**2)
    phase = 2 * bf.const_pi() / BigFloat(waveLen) * distance
    phase = bf.mod(phase, 2 * bf.const_pi())
    return phase
コード例 #6
0
ファイル: elliptic_curve.py プロジェクト: kebding/crypto
 def hasses_bound(self):
     ''' EC.hasses_bound
     this function returns a tuple indicating the interval of Hasse's Theorem
     for the curve with a modulus of p:
         p + 1 - 2*sqrt(p) <= num points on curve <= p + 1 + 2*sqrt(p)
     in order to support finding the bounds for large curves, this function
     utilizes the bigfloat libary and returns a bigfloat object.
     inputs:
         none
     returns:
         tuple (lowerbound, upperbound)
     '''
     mod_sqrt = bigfloat.sqrt(self.mod)
     lower = self.mod + 1 - (2 * mod_sqrt)
     upper = self.mod + 1 + (2 * mod_sqrt)
     return (lower, upper)
コード例 #7
0
def checkExtendedFarFieldConstraint(sim, detector, waveLen):
    """Check the errors when the ray is not really going to the top of the detector cell"""
    # l2 is the actual ray going to the bottom of the detector cell (furthes away from top)
    # l1 is the ref ray going to the top of the cell
    # l2_ is the modified l2 to top of cell and l1_ the modified ref ray to the target pt of l2
    maxAnglesTop = detector.anglePerCell * detector.size / 2
    maxAnglesBottom = maxAnglesTop - detector.anglePerCell
    # SimZ = DetX, SimY = DetY
    maxAnglesTop = np.flipud(maxAnglesTop)
    maxAnglesBottom = np.flipud(maxAnglesBottom)
    # This is what we acutally want
    (l1, l2_,
     l1l2_Diff) = calcRayLengthsAndFarFieldDiff(maxAnglesTop, sim.size[1:] / 2,
                                                sim, detector)
    # This is what we easily get
    (l1_, l2,
     l1_l2Diff) = calcRayLengthsAndFarFieldDiff(maxAnglesBottom,
                                                sim.size[1:] / 2, sim,
                                                detector)
    # 1: |(l2_-l1) - (l2-l1_)| <<(!) waveLen
    cellError = bf.abs((l2_ - l1) - (l2 - l1_))
    print("cellError=", cellError,
          "OK" if cellError < 0.05 * waveLen else "ERROR")
    # 2: |(l2_-l1) - l1_l2Diff| <<(!) waveLen (Projection used)
    projError = bf.abs((l2_ - l1) - l1_l2Diff)
    print("projError=", projError,
          "OK" if projError < 0.05 * waveLen else "ERROR")
    # 3: Try reverse projection: Project onto ref ray as its angles are known
    vecRefRay = np.array([bf.tan(maxAnglesTop[0]),
                          bf.tan(maxAnglesTop[1])]) * detector.distance
    lRef = bf.sqrt(detector.distance**2 + vecRefRay[0]**2 + vecRefRay[1]**2)
    lReverseProjDiff = np.dot(vecRefRay,
                              sim.size[1:] / 2 * sim.cellSize[1:]) / lRef
    revProjError = bf.abs((l2_ - l1) - lReverseProjDiff)
    print("revProjError=", revProjError,
          "OK" if revProjError < 0.05 * waveLen else "ERROR")
コード例 #8
0
 def test_sqrt_helper(ans, a):
     u = bigfloat.Number(ans)
     v = bigfloat.Number(a)
     self.assertEqual(u, bigfloat.sqrt(v))
コード例 #9
0
ファイル: euler_587_v1.py プロジェクト: vermuz/project-euler
 def diff(x):
     return (calc_y1(x) - (1 - sqrt(1 - (1 - x)**2)))
コード例 #10
0
#!/usr/bin/env python

from bigfloat import sqrt, precision
from pe_tools import is_square

def hundred_digit_sum(n):
    s = str(n)
    if '.' in s:
        i = s.find('.')
        s = s[:i] + s[i+1:]
    s = s[:100]
    return sum(map(int, s))

if __name__ == '__main__':
    total = 0
    for n in range(1, 100):
        if not is_square(n):
            s = hundred_digit_sum(sqrt(n, precision(340)))
            total += s
    print str(total)
コード例 #11
0
def y32(n):
    return a1_32 * np.float32((1 + sqrt(5)) / 2)**n - a2_32 * np.float32(
        (1 - sqrt(5)) / 2)**n
コード例 #12
0
def y64(n):
    return a1_64 * ((1 + sqrt(5)) / 2)**n - a2_64 * ((1 - sqrt(5)) / 2)**n
コード例 #13
0
from env import *
from bigfloat import sqrt, precision

n_max = 50

fib32 = [np.float32(1), np.float32((1 - sqrt(5)) / 2)]
for i in range(0, n_max - 2):
    fib32.append(np.float32(fib32[i] + fib32[i + 1]))

fib64 = [np.float64(1), np.float64((1 - sqrt(5)) / 2)]
for i in range(0, n_max - 2):
    fib64.append(np.float64(fib64[i] + fib64[i + 1]))

print(fib32)
print(fib64)

plt.figure(figsize=FIG_SIZE_2D, dpi=FIG_DPI_2D)
plt.plot(list(range(n_max)),
         np.abs(fib32),
         'ro',
         color='blue',
         label='float32')
plt.plot(list(range(n_max)), np.abs(fib64), 'rx', color='red', label='float64')
plt.yscale('log')
plt.grid(**GRID_OPTIONS)
plt.legend(loc='upper center')
plt.xlabel('n')
plt.ylabel('$\log_{10} |y_n|$')
plt.savefig('./figs/02-fibonacci-c.eps', dpi=SAVE_FIG_DPI)
#plt.show()
コード例 #14
0
    def testInterference(self):
        cmakeFlags = os.environ["TEST_CMAKE_FLAGS"].split(" ")
        paramOverwrites = None
        for flag in cmakeFlags:
            if flag.startswith("-DPARAM_OVERWRITES:LIST"):
                paramOverwrites = flag.split("=", 1)[1].split(";")

        params = ParamParser()
        if paramOverwrites:
            for param in paramOverwrites:
                if param.startswith("-D"):
                    param = param[2:].split("=")
                    params.AddDefine(param[0], param[1])
        params.ParseFolder(os.environ["TEST_OUTPUT_PATH"] +
                           "/simulation_defines/param")

        params.SetCurNamespace("parataxis::detector::PhotonDetector")
        detector = scatter.DetectorData(
            [],
            [params.GetNumber("cellWidth"),
             params.GetNumber("cellHeight")], params.GetNumber("distance"))
        self.assertEqual(params.GetValue("IncomingParticleHandler"),
                         "particleHandlers::AddWaveParticles")

        params.SetCurNamespace(
            "parataxis::particles::scatterer::direction::Fixed")
        scatterAngles = [
            params.GetNumber("angleY"),
            params.GetNumber("angleZ")
        ]

        params.SetCurNamespace("parataxis::initialDensity")
        self.assertEqual(params.GetValue("Generator"),
                         "AvailableGenerators::DoublePoint")
        params.SetCurNamespace(
            "parataxis::initialDensity::AvailableGenerators::DoublePoint")
        scatterParticle1 = scatter.ParticleData([
            params.GetNumber("offsetX"),
            params.GetNumber("offsetY"),
            params.GetNumber("offsetZ1")
        ], scatterAngles)
        scatterParticle2 = scatter.ParticleData([
            params.GetNumber("offsetX"),
            params.GetNumber("offsetY"),
            params.GetNumber("offsetZ2")
        ], scatterAngles)

        params.SetCurNamespace("parataxis")
        simulation = scatter.SimulationData(
            list(map(int, os.environ["TEST_GRID_SIZE"].split(" "))), [
                params.GetNumber("SI::CELL_WIDTH"),
                params.GetNumber("SI::CELL_HEIGHT"),
                params.GetNumber("SI::CELL_DEPTH")
            ])

        pulseLen = np.floor(
            params.GetNumber("laserConfig::PULSE_LENGTH") /
            params.GetNumber("SI::DELTA_T"))
        self.assertEqual(
            params.GetValue("laserConfig::distribution::UsedValue"),
            "EqualToPhotons")
        numPartsPerTsPerCell = params.GetNumber(
            "laserConfig::photonCount::Const::numPhotons")
        waveLen = params.GetNumber("wavelengthPhotons",
                                   getFromValueIdentifier=True)
        #print("Wavelen=", waveLen)

        with open(
                os.environ["TEST_BASE_BUILD_PATH"] + "/" +
                os.environ["TEST_NAME"] + "_detector.tif", 'rb') as imFile:
            im = Image.open(imFile)
            detector.resize(im.size)

            self.assertTrue(
                scatter.checkFarFieldConstraint(simulation, detector, waveLen))

            ## Calculation
            posOnDet1 = scatter.getBinnedDetCellIdx(scatterParticle1, detector,
                                                    simulation)
            posOnDet2 = scatter.getBinnedDetCellIdx(scatterParticle2, detector,
                                                    simulation)
            np.testing.assert_allclose(posOnDet1, posOnDet2)

            ## Checks
            imgData = np.array(im)
            whitePts = np.transpose(np.where(imgData > 1.e-3))
            print(len(whitePts), "white pixels at:", whitePts)
            self.assertEqual(len(whitePts), 1)
            self.checkCoordinate(whitePts[0], posOnDet1)

            phi1 = scatter.calcPhase(scatterParticle1, detector, simulation,
                                     waveLen)
            phi2 = scatter.calcPhase(scatterParticle2, detector, simulation,
                                     waveLen)
            real = bf.cos(phi1) + bf.cos(phi2)
            imag = bf.sin(phi1) + bf.sin(phi2)
            sqrtIntensity = bf.sqrt(real * real + imag * imag)
            sqrtIntensityPerTs = sqrtIntensity * numPartsPerTsPerCell
            #print("Phis:", phi1, phi2, "Diff", phi1-phi2, "SqrtIntensityPerTs", sqrtIntensityPerTs)
            expectedDetCellValue = float(bf.sqr(sqrtIntensityPerTs * pulseLen))
            np.testing.assert_allclose(imgData[tuple(whitePts[0])],
                                       expectedDetCellValue,
                                       rtol=1e-3)
コード例 #15
0
from bigfloat import sub, add, mul, div, sqr, sqrt, precision

a=1e-8
b=10
c=1e-8
p = 100

D = sub(sqr(b) , mul(4, mul(a,c) ), precision(p))

x1 = div( - add(b , sqrt(D, precision(p))) , mul(2,a), precision(p))
x2 = div( - sub(b , sqrt(D, precision(p))) , mul(2,a), precision(p))

print x1,x2
コード例 #16
0
 def __calculate_fraction(self):
     powered_pi = self.__double_pi_powered_by(self.__d)
     return BigFloat.exact('1', precision=110) / bigfloat.sqrt(
         (powered_pi * self.__multiply_sigma()))