Python math.e() Examples

The following are code examples for showing how to use math.e(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_callbacks.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_callback_register_double(self):
        # Issue #8275: buggy handling of callback args under Win64
        # NOTE: should be run on release builds as well
        dll = CDLL(_ctypes_test.__file__)
        CALLBACK = CFUNCTYPE(c_double, c_double, c_double, c_double,
                             c_double, c_double)
        # All this function does is call the callback with its args squared
        func = dll._testfunc_cbk_reg_double
        func.argtypes = (c_double, c_double, c_double,
                         c_double, c_double, CALLBACK)
        func.restype = c_double

        def callback(a, b, c, d, e):
            return a + b + c + d + e

        result = func(1.1, 2.2, 3.3, 4.4, 5.5, CALLBACK(callback))
        self.assertEqual(result,
                         callback(1.1*1.1, 2.2*2.2, 3.3*3.3, 4.4*4.4, 5.5*5.5))


################################################################ 
Example 2
Project: redrum   Author: Evidlo   File: redrum.py    MIT License 6 votes vote down vote up
def set_wallpaper(config, image):

    print("Applying wallpaper")

    # download image to `image`
    try:
        response = requests.get(image['link'])
        if response.status_code == 200:
            with open(config.image_file, 'wb') as f:
                f.write(response.content)
        else:
            logging.error("Got response {} when downloading image.".format(reponse.status_code))
    except ConnectionError:
        logging.error("Connection error")
        sys.exit()

    try:
        subprocess.check_output(config.wallpaper_command.format(image_file=config.image_file), shell=True)
    except subprocess.CalledProcessError as e:
        logger.error("Command `{}` failed with status {}".format(e.cmd, e.returncode))
        sys.exit()


# save date, options, seen images and images to cache 
Example 3
Project: MFEprimer_linux   Author: nick-youngblut   File: TmDeltaG.py    MIT License 6 votes vote down vote up
def calDeltaG(qseq, sseq, mono_conc=50, diva_conc=1.5, dntp_conc=0.25, deltaH=None, deltaS=None): 
    """ Calculate the free Gibbs energy """

    mono_conc = float(mono_conc)
    diva_conc = float(diva_conc)
    dntp_conc = float(dntp_conc)

    if not (deltaH and deltaS):
	deltaH, deltaS = calDeltaHS(qseq, sseq)

    # Calculate the free Gibbs energy
    tao = 273.15 + 37 # Constant temperature tao in Kelvin

    # Many thanks for the anonymous referee who help me fix the bug in last version.
    mono_conc = mono_conc + divalent2monovalent(diva_conc, dntp_conc)
    mono_conc = mono_conc / 1000

    deltaS_adjust = deltaS + 0.368 * (len(sseq) - 1) * math.log(mono_conc, math.e)

    deltaG = (deltaH * 1000 - tao * deltaS_adjust) / 1000
    return deltaG 
Example 4
Project: MFEprimer_linux   Author: nick-youngblut   File: TmDeltaG.py    MIT License 6 votes vote down vote up
def calTm(qseq, sseq, mono_conc=50, diva_conc=1.5, oligo_conc=50, dntp_conc=0.25, deltaH=None, deltaS=None):
    """ Calculate Tm value of amplicon"""

    mono_conc = float(mono_conc)
    diva_conc = float(diva_conc)
    oligo_conc = float(oligo_conc)
    dntp_conc = float(dntp_conc)

    if not (deltaH and deltaS):
	deltaH, deltaS = calDeltaHS(qseq, sseq)

    deltaH = deltaH * 1000

    oligo_conc = oligo_conc / 1000000000

    # Many thanks for the anonymous referee who help me fix the bug in last version.
    mono_conc = mono_conc + divalent2monovalent(diva_conc, dntp_conc)
    mono_conc = mono_conc / 1000

    deltaS = deltaS + 0.368 * (len(qseq) - 1) * math.log(mono_conc, math.e)

    Tm = deltaH / (deltaS + 1.987 * math.log(oligo_conc / 4, math.e)) - 273.15

    return Tm 
Example 5
Project: synspy   Author: informatics-isi-edu   File: util.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dense_segment_status(centroids, sparse_centroids, sparse_status):
    """Construct dense segment status from sparse info, e.g. previously loaded from CSV."""
    # assume that dump is ordered subset of current analysis
    status = np.zeros((centroids.shape[0],), dtype=np.uint8)

    i = 0
    for row in range(sparse_centroids.shape[0]):
        # scan forward until we find same centroid in sparse subset
        while i < centroids.shape[0] and tuple(sparse_centroids[row]) != tuple(centroids[i]):
            i += 1

        if i >= centroids.shape[0]:
            raise ValueError("Sparse dump does not match image analysis!", sparse_centroids[row])

        if sparse_status[row]:
            status[i] = sparse_status[row]

    return status 
Example 6
Project: raveberry   Author: raveberry   File: color_programs.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, lights):
        super().__init__(lights)
        self.name = 'Rave'

        self.cava_fifo_path = os.path.join(settings.BASE_DIR, 'config/cava_fifo')

        # Keep these configurations in sync with config/cava.config
        self.bars = 16
        self.bit_format = 8

        self.frame_length = self.bars * (self.bit_format // 8)
        # RING
        # map the leds to rainbow colors from red over green to blue (without pink-> hue values in [0, ⅔]
        # stretch the outer regions (red and blue) and compress the inner region (green)
        led_count = self.lights.ring.LED_COUNT
        hues = [2/3 * 1 / (1 + math.e**(-4*math.e*(led/(led_count-1)-0.5))) for led in range(0, led_count)]
        self.base_colors = [colorsys.hsv_to_rgb(hue, 1, 1) for hue in hues]

        # STRIP
        # distribute frequencies over the three leds. Don't use hard cuts, but smooth functions
        # the functions add up to one at every point and each functions integral is a third
        self.red_coeffs = [-1 / (1 + math.e**(-6*math.e*(led/(led_count-1)-1/3))) + 1 for led in range(0, self.frame_length)]
        self.blue_coeffs = [1 / (1 + math.e**(-6*math.e*(led/(led_count-1)-2/3))) for led in range(0, self.frame_length)]
        self.green_coeffs = [1 - self.red_coeffs[led] - self.blue_coeffs[led] for led in range(0, self.frame_length)] 
Example 7
Project: raveberry   Author: raveberry   File: color_programs.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def start(self):
        self.current_frame = [0 for led in range(self.lights.ring.LED_COUNT)]
        self.growing_frame = b''
        try:
            # delete old contents of the pipe
            os.remove(self.cava_fifo_path)
        except FileNotFoundError as e:
            # the file does not exist
            pass
        try:
            os.mkfifo(self.cava_fifo_path)
        except FileExistsError as e:
            # the file already exists
            print(self.cava_fifo_path + ' already exists while starting')

        self.cava = subprocess.Popen(['cava', '-p', os.path.join(settings.BASE_DIR, 'config/cava.config')], cwd=settings.BASE_DIR)
        #cava_fifo = open(cava_fifo_path, 'r')
        self.cava_fifo = os.open(self.cava_fifo_path, os.O_RDONLY | os.O_NONBLOCK) 
Example 8
Project: raveberry   Author: raveberry   File: color_programs.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def compute(self):
        # read the fifo until we get to the current frame
        while True:
            try:
                read = os.read(self.cava_fifo, self.frame_length - len(self.growing_frame))
                if read == b'':
                    return
                self.growing_frame += read
            except OSError as e:
                if e.errno == errno.EAGAIN or e.errno == errno.EWOULDBLOCK:
                    # there were not enough bytes for a whole frame, keep the old frame
                    return
                else:
                    raise

            # we read a whole frame, update the factors
            if len(self.growing_frame) == self.frame_length:
                self.current_frame = [int(b) / 255 for b in self.growing_frame]
                self.growing_frame = b'' 
Example 9
Project: NiujiaoDebugger   Author: MrSrc   File: test_callbacks.py    GNU General Public License v3.0 6 votes vote down vote up
def test_callback_register_double(self):
        # Issue #8275: buggy handling of callback args under Win64
        # NOTE: should be run on release builds as well
        dll = CDLL(_ctypes_test.__file__)
        CALLBACK = CFUNCTYPE(c_double, c_double, c_double, c_double,
                             c_double, c_double)
        # All this function does is call the callback with its args squared
        func = dll._testfunc_cbk_reg_double
        func.argtypes = (c_double, c_double, c_double,
                         c_double, c_double, CALLBACK)
        func.restype = c_double

        def callback(a, b, c, d, e):
            return a + b + c + d + e

        result = func(1.1, 2.2, 3.3, 4.4, 5.5, CALLBACK(callback))
        self.assertEqual(result,
                         callback(1.1*1.1, 2.2*2.2, 3.3*3.3, 4.4*4.4, 5.5*5.5)) 
Example 10
Project: cyrapidjson   Author: thedrow   File: test_params.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_use_decimal():
    import math
    from decimal import Decimal

    dstr = "2.7182818284590452353602874713527"
    d = Decimal(dstr)

    with pytest.raises(TypeError):
        rapidjson.dumps(d)

    assert rapidjson.dumps(float(dstr)) == str(math.e)
    assert rapidjson.dumps(d, use_decimal=True) == dstr
    assert rapidjson.dumps({"foo": d}, use_decimal=True) == '{"foo":%s}' % dstr

    assert rapidjson.loads(
            rapidjson.dumps(d, use_decimal=True),
            use_decimal=True) == d

    assert rapidjson.loads(rapidjson.dumps(d, use_decimal=True)) == float(dstr) 
Example 11
Project: HEG_ESP32   Author: moothyknight   File: simplegraphs.py    MIT License 6 votes vote down vote up
def UpdateMovie(self, data, times):
        self.midplot.Update(data[-320:], numpy.array(times[-320:]) - times[0], zero_x=False)
        
        delta = mean(data[-5:]) - mean(data[-50:])
        sigma = numpy.std(data[-300:])
        
        contrast = 1./(1+math.e**(-delta/sigma*5.))*100. - 85.
        zoom     = 1./(1+math.e**(-delta/sigma*2.))
        
        trend = 1./(1+math.e**(-delta/sigma)) * 2 - 1

        r = int((1-max(-trend, 0))*64)
        g = int((1-math.fabs(trend))*64)
        b = int((1-max( trend, 0))*64)
        if trend < 0:
            b = 95 + int(-trend*160)
        else:
            r = 95 + int(trend*160)
        self.trendmeter.SetColor(wx.Color(r,g,b))
        self.trendmeter.SetValue(trend)
        
        InstrumentsPanel.UpdateMovie(self, data, times) 
Example 12
Project: HEG_ESP32   Author: moothyknight   File: hegmovie.py    MIT License 6 votes vote down vote up
def OnUpdate(self, data, times=[]):
        pass
#        delta = mean(data[-5:]) - mean(data[-50:])
#        sigma = numpy.std(data[-300:])
        
#        contrast = 1./(1+math.e**(-delta/sigma*5. - 0))*100. - 85.
#        self.Brightness(contrast, 1)
#        #if not random.randint(0, 30) and DEBUG: print contrast, delta, sigma
        
#        if   delta > -sigma/5:#-0.25:
#            if self.paused:
#                self.paused = False
#                self.pausing = False
#                self.Pause()
#                #if DEBUG: print "Now unpaused, %10.3f, %3.3f" % (time.time(), contrast)
#        elif delta < -sigma/4:
#            if not self.paused:
#                self.paused = True
#                self.pausing = True
#                self.Pause()
#                #if DEBUG: print "Now paused,   %10.3f" % time.time() 
Example 13
Project: PySail-426   Author: j3b4   File: SimulazioneRegata300.py    GNU General Public License v3.0 6 votes vote down vote up
def calcolaventogeostroficoCentroAzione(PCentroAzione,LatCentroAzione,LonCentroAzione,lamba,lat,lon):
    #campo di alta pressione: P=(H-1013)*cos(2pi/lamba*r)+1013, per r<=lamba/2, P=1013 per r >lamba/2
    #campo di bassa pressione: P=(1013-L)*cos(2pi/lamba*r+pi/2)+L, per r<=lamba/2, P=1013 per r>lamba/2
    #r distanza dal centro d'azione e raggio curvatura isobara
    losso=lossodromica(LatCentroAzione,LonCentroAzione,lat,lon)
    r=losso[0]
    brg=losso[1]
    tws=0
    twd=0
    segno=0
    if r<0.5*lamba:
        if PCentroAzione>1013:
            GradientePressione=-(PCentroAzione-1013)*2*math.pi/lamba*math.sin(2*math.pi/lamba*r)
            segno=1
        else:
            GradientePressione=-(1013-PCentroAzione)*2*math.pi/lamba*math.sin(2*math.pi/lamba*r)
            segno=-1
        tws=calcolaventogeostrofico(LatCentroAzione,GradientePressione,r)
        
        if LatCentroAzione>0:
            twd=riduci360(brg-segno*math.pi/2)#emisfero Nord
        else:
            twd=riduci360(brg+segno*math.pi/2)#emisfero Sud
    return tws,twd 
Example 14
Project: PySail-426   Author: j3b4   File: SimulazioneRegata316.py    GNU General Public License v3.0 6 votes vote down vote up
def ventogeostroficoCentroAzione(PCentroAzione,LatCentroAzione,LonCentroAzione,extension,lat,lon):
    #campo di pressione: P=0.5*(PCentro-1013)*cos(pi/extension*r)+(PCentro+1013)*0.5, per r<=extension, P=1013 per r >extension
    #r distanza dal centro d'azione e raggio curvatura isobara
    losso=lossodromica(LatCentroAzione,LonCentroAzione,lat,lon)
    r=losso[0]
    brg=losso[1]
    tws=0
    twd=0
    segno=0
    exp=0
    if r<extension:
        if PCentroAzione>1013:
            segno=1
        else:
            segno=-1
        #GradientePressione=-0.5*(PCentroAzione-1013)*math.pi/extension*math.sin(math.pi/extension*r)
        GradientePressione=0.5*(PCentroAzione-1013)*math.pi/extension*math.sin(math.pi/extension*r)
        GradientePressione=math.copysign(GradientePressione,1)
        tws=ventogeostrofico(LatCentroAzione,segno*GradientePressione,r)
        if LatCentroAzione>0:
            twd=riduci360(brg-segno*math.radians(100))#emisfero Nord
        else:
            twd=riduci360(brg+segno*math.radians(100))#emisfero Sud
    return tws,twd 
Example 15
Project: PySail-426   Author: j3b4   File: SimulazioneRegata316.py    GNU General Public License v3.0 6 votes vote down vote up
def ventogeostroficoCentroAzione(PCentroAzione,LatCentroAzione,LonCentroAzione,extension,lat,lon):
    #campo di pressione: P=0.5*(PCentro-1013)*cos(pi/extension*r)+(PCentro+1013)*0.5, per r<=extension, P=1013 per r >extension
    #r distanza dal centro d'azione e raggio curvatura isobara
    losso=lossodromica(LatCentroAzione,LonCentroAzione,lat,lon)
    r=losso[0]
    brg=losso[1]
    tws=0
    twd=0
    segno=0
    exp=0
    if r<extension:
        if PCentroAzione>1013:
            segno=1
        else:
            segno=-1
        #GradientePressione=-0.5*(PCentroAzione-1013)*math.pi/extension*math.sin(math.pi/extension*r)
        GradientePressione=0.5*(PCentroAzione-1013)*math.pi/extension*math.sin(math.pi/extension*r)
        GradientePressione=math.copysign(GradientePressione,1)
        tws=ventogeostrofico(LatCentroAzione,segno*GradientePressione,r)
        if LatCentroAzione>0:
            twd=riduci360(brg-segno*math.radians(100))#emisfero Nord
        else:
            twd=riduci360(brg+segno*math.radians(100))#emisfero Sud
    return tws,twd 
Example 16
Project: PySail-426   Author: j3b4   File: Navigation.py    GNU General Public License v3.0 6 votes vote down vote up
def offset(latA, lonA, Distance, Heading):
    # Takes a position (lat,lon)
    # a distance in nautical miles and a direction in 0-360
    # calculates where you would end up if you started a journey at that
    # heading and moved in a "straight line" (Great Circle)
    # Does not function correctly near the poles
    # I think this is the cosine method
    # haversine would be more accurate
    a = Distance * 1.0 / EARTH_RADIUS
    latB = latA + a * math.cos(Heading)
    if math.copysign(latA-latB, 1) <= math.radians(0.1/3600.0):
        q = math.cos(latA)
    else:
        Df = math.log(math.tan(latB/2+math.pi/4)
                      / math.tan(latA/2+math.pi/4),
                      math.e)
        q = (latB - latA) / Df
    lonB = lonA - a * math.sin(Heading) / q
    return latB, lonB 
Example 17
Project: PySail-426   Author: j3b4   File: Navigation.py    GNU General Public License v3.0 6 votes vote down vote up
def loxodrome(latA, lonA, latB, lonB):  # lossodromica
    # Rhumb line navigation
    # Takes two points on earth and returns:
    # the distance and constant (true) bearing one would need to
    # follow to reach it.
    # Doesn't function near poles:
    # but you shouldn't be sailing near the poles anyways!
    # when latB = -90: math domain error log(0)
    # when latA = -90 [zero divison error]
    # when A==B returns (0.0,0.0)
    # if latA == latB:
    if math.copysign(latA-latB, 1) <= math.radians(0.1/3600.0):
        q = math.cos(latA)
    else:
        Df = math.log(math.tan(latB/2+math.pi/4)
                      / math.tan(latA/2+math.pi/4), math.e)
        q = (latB-latA) * 1.0/Df
    Distance = EARTH_RADIUS * ((latA-latB)**2+(q*(lonA-lonB))**2)**0.5
    Heading = math.atan2(-q*(lonB-lonA), (latB-latA))
    if Heading < 0:
        Heading = Heading + 2.0 * math.pi  # atan2:[-pi,pi]
    return Distance, Heading 
Example 18
Project: ironpython2   Author: IronLanguages   File: test_callbacks.py    Apache License 2.0 6 votes vote down vote up
def test_callback_register_double(self):
        # Issue #8275: buggy handling of callback args under Win64
        # NOTE: should be run on release builds as well
        dll = CDLL(_ctypes_test.__file__)
        CALLBACK = CFUNCTYPE(c_double, c_double, c_double, c_double,
                             c_double, c_double)
        # All this function does is call the callback with its args squared
        func = dll._testfunc_cbk_reg_double
        func.argtypes = (c_double, c_double, c_double,
                         c_double, c_double, CALLBACK)
        func.restype = c_double

        def callback(a, b, c, d, e):
            return a + b + c + d + e

        result = func(1.1, 2.2, 3.3, 4.4, 5.5, CALLBACK(callback))
        self.assertEqual(result,
                         callback(1.1*1.1, 2.2*2.2, 3.3*3.3, 4.4*4.4, 5.5*5.5)) 
Example 19
Project: pyblish-win   Author: pyblish   File: test_callbacks.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_float(self):
        # only almost equal: double -> float -> double
        import math
        self.check_type(c_float, math.e)
        self.check_type(c_float, -math.e) 
Example 20
Project: pyblish-win   Author: pyblish   File: test_callbacks.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_callback_register_int(self):
        # Issue #8275: buggy handling of callback args under Win64
        # NOTE: should be run on release builds as well
        dll = CDLL(_ctypes_test.__file__)
        CALLBACK = CFUNCTYPE(c_int, c_int, c_int, c_int, c_int, c_int)
        # All this function does is call the callback with its args squared
        func = dll._testfunc_cbk_reg_int
        func.argtypes = (c_int, c_int, c_int, c_int, c_int, CALLBACK)
        func.restype = c_int

        def callback(a, b, c, d, e):
            return a + b + c + d + e

        result = func(2, 3, 4, 5, 6, CALLBACK(callback))
        self.assertEqual(result, callback(2*2, 3*3, 4*4, 5*5, 6*6)) 
Example 21
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testConstants(self):
        self.ftest('pi', math.pi, 3.1415926)
        self.ftest('e', math.e, 2.7182818) 
Example 22
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testExp(self):
        self.assertRaises(TypeError, math.exp)
        self.ftest('exp(-1)', math.exp(-1), 1/math.e)
        self.ftest('exp(0)', math.exp(0), 1)
        self.ftest('exp(1)', math.exp(1), math.e)
        self.assertEqual(math.exp(INF), INF)
        self.assertEqual(math.exp(NINF), 0.)
        self.assertTrue(math.isnan(math.exp(NAN))) 
Example 23
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testLog1p(self):
        self.assertRaises(TypeError, math.log1p)
        self.ftest('log1p(1/e -1)', math.log1p(1/math.e-1), -1)
        self.ftest('log1p(0)', math.log1p(0), 0)
        self.ftest('log1p(e-1)', math.log1p(math.e-1), 1)
        self.ftest('log1p(1)', math.log1p(1), math.log(2))
        self.assertEqual(math.log1p(INF), INF)
        self.assertRaises(ValueError, math.log1p, NINF)
        self.assertTrue(math.isnan(math.log1p(NAN)))
        n= 2**90
        self.assertAlmostEqual(math.log1p(n), 62.383246250395075)
        self.assertAlmostEqual(math.log1p(n), math.log1p(float(n))) 
Example 24
Project: redrum   Author: Evidlo   File: redrum.py    MIT License 5 votes vote down vote up
def logistic_function(x, midpoint, k):
    return (1 + pow(math.e, -k * (1 - midpoint))) / (1 + pow(math.e, -k * (x - midpoint)))

# calculate a score for an image 
Example 25
Project: soccer-matlab   Author: utra-robosoccer   File: utility.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def diag_normal_entropy(mean, logstd):
  """Empirical entropy of a normal with diagonal covariance."""
  constant = mean.shape[-1].value * math.log(2 * math.pi * math.e)
  return (constant + tf.reduce_sum(2 * logstd, 1)) / 2 
Example 26
Project: soccer-matlab   Author: utra-robosoccer   File: utility.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def diag_normal_entropy(mean, logstd):
  """Empirical entropy of a normal with diagonal covariance."""
  constant = mean.shape[-1].value * math.log(2 * math.pi * math.e)
  return (constant + tf.reduce_sum(2 * logstd, 1)) / 2 
Example 27
Project: synspy   Author: informatics-isi-edu   File: util.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def Gsigma(sigma):
    """Pickle a gaussian function G(x) for given sigma"""
    def G(x):
        return (math.e ** (-(x**2)/(2*sigma**2)))/(2 * math.pi* sigma**2)**0.5
    return G 
Example 28
Project: synspy   Author: informatics-isi-edu   File: util.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def centroids_zx_swap(centroids):
    """Return a copy of centroids array with Z and X swapped, e.g. ZYX<->XYZ."""
    copy = np.zeros(centroids.shape, dtype=centroids.dtype)
    copy[:,0] = centroids[:,2]
    copy[:,1] = centroids[:,1]
    copy[:,2] = centroids[:,0]
    return copy 
Example 29
Project: Audio_Effects_Suite   Author: bmroach   File: mainReverb.py    Apache License 2.0 5 votes vote down vote up
def reverb(signal, preDelay = 0, Decay = .25, trim = True):
    """fileName: name of file in string form
        preDelay: delay before reverb begins (seconds)
        Decay: hang time of signal (seconds)        
    """    
    signal = [int(x) for x in signal]
    
    pdSamples = int(preDelay * sampleRate)
    dSamples = int(Decay * sampleRate)
    
    if trim: #trim to 10 seconds  
        signal = signal[:441000]        
     
    
    lengthIn = len(signal)
    logArray = [(math.e**(-1*(x/dSamples))) for x in range(dSamples)]
    avg = ut.signalAvg(signal)[0]
    goalAmp = avg * 1.2
    outputSignal = [0 for x in range(len(signal) + pdSamples + dSamples)]
    length = len(outputSignal)
    
    for i in range(lengthIn): #for all input samples
        currentSample = signal[i]        
        outputSignal[i] = currentSample
        
        for x in range(1,dSamples): #for all reverb samples
            index = i + x + pdSamples            
            outputSignal[index] += (currentSample * logArray[x])
                
    
    while ut.signalAvg(outputSignal)[0] > goalAmp:
        outputSignal = [x*.90 for x in outputSignal]
    
    outputSignal = [int(x) for x in outputSignal]
     
    return outputSignal 
Example 30
Project: cb4   Author: joint-online-judge   File: difficulty.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _LOGP(x: float):
  sqrt_2_pi = 2.506628274631000502415765284811 # math.sqrt(2 * math.pi)
  return math.exp(-1.0 * pow(math.log(x, math.e), 2) / 0.5) / x / 0.5 / sqrt_2_pi 
Example 31
Project: raveberry   Author: raveberry   File: color_programs.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def stop(self):
        try:
            os.close(self.cava_fifo)
        except OSError as e:
            print('cava fifo already closed: ' + str(e))
        except TypeError as e:
            print('cava fifo does not exist: ' + str(e))

        self.cava.terminate()

        try:
            os.remove(self.cava_fifo_path)
        except FileNotFoundError as e:
            # the file was already deleted
            print(self.cava_fifo_path + ' not found while deleting: ' + str(e)) 
Example 32
Project: NiujiaoDebugger   Author: MrSrc   File: test_callbacks.py    GNU General Public License v3.0 5 votes vote down vote up
def test_float(self):
        # only almost equal: double -> float -> double
        import math
        self.check_type(c_float, math.e)
        self.check_type(c_float, -math.e) 
Example 33
Project: NiujiaoDebugger   Author: MrSrc   File: test_callbacks.py    GNU General Public License v3.0 5 votes vote down vote up
def test_callback_register_int(self):
        # Issue #8275: buggy handling of callback args under Win64
        # NOTE: should be run on release builds as well
        dll = CDLL(_ctypes_test.__file__)
        CALLBACK = CFUNCTYPE(c_int, c_int, c_int, c_int, c_int, c_int)
        # All this function does is call the callback with its args squared
        func = dll._testfunc_cbk_reg_int
        func.argtypes = (c_int, c_int, c_int, c_int, c_int, CALLBACK)
        func.restype = c_int

        def callback(a, b, c, d, e):
            return a + b + c + d + e

        result = func(2, 3, 4, 5, 6, CALLBACK(callback))
        self.assertEqual(result, callback(2*2, 3*3, 4*4, 5*5, 6*6)) 
Example 34
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def testConstants(self):
        # Ref: Abramowitz & Stegun (Dover, 1965)
        self.ftest('pi', math.pi, 3.141592653589793238462643)
        self.ftest('e', math.e, 2.718281828459045235360287)
        self.assertEqual(math.tau, 2*math.pi) 
Example 35
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def testLog(self):
        self.assertRaises(TypeError, math.log)
        self.ftest('log(1/e)', math.log(1/math.e), -1)
        self.ftest('log(1)', math.log(1), 0)
        self.ftest('log(e)', math.log(math.e), 1)
        self.ftest('log(32,2)', math.log(32,2), 5)
        self.ftest('log(10**40, 10)', math.log(10**40, 10), 40)
        self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2)
        self.ftest('log(10**1000)', math.log(10**1000),
                   2302.5850929940457)
        self.assertRaises(ValueError, math.log, -1.5)
        self.assertRaises(ValueError, math.log, -10**1000)
        self.assertRaises(ValueError, math.log, NINF)
        self.assertEqual(math.log(INF), INF)
        self.assertTrue(math.isnan(math.log(NAN))) 
Example 36
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def test_identical_infinite(self):
        # these are close regardless of tolerance -- i.e. they are equal
        self.assertIsClose(INF, INF)
        self.assertIsClose(INF, INF, abs_tol=0.0)
        self.assertIsClose(NINF, NINF)
        self.assertIsClose(NINF, NINF, abs_tol=0.0) 
Example 37
Project: gymwipe   Author: bjoluc   File: physical.py    GNU General Public License v3.0 5 votes vote down vote up
def approxQFunction(x: float) -> float:
    """
    Approximates the gaussian Q-Function for :math:`x \\ge 0` by using the
    following formula, derived from :cite:`karagiannidis2007improved`:

    :math:`Q(x)\\approx\\frac{\\left( 1-e^{-1.4x}\\right)
    e^{-\\frac{x^{2}}{2}}}{1.135\\sqrt{2\\pi}x}`

    Args:
        x: The :math:`x` value to approximate :math:`Q(x)` for
    """
    assert x >= 0
    return (1 - e**(-1.4*x)) * e**(-(x**2 / 2)) / (1.135 * sqrtOfTwoPi * x) 
Example 38
Project: gymwipe   Author: bjoluc   File: physical.py    GNU General Public License v3.0 5 votes vote down vote up
def completed(self):
        """
        Returns ``True`` if the transmission has completed (i.e. the current
        simulation time >= stopTime)
        """
        return SimMan.now >= self.stopTime 
Example 39
Project: vj4   Author: vijos   File: difficulty.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _LOGP(x: float):
  sqrt_2_pi = 2.506628274631000502415765284811 # math.sqrt(2 * math.pi)
  return math.exp(-1.0 * pow(math.log(x, math.e), 2) / 0.5) / x / 0.5 / sqrt_2_pi 
Example 40
Project: litmus-site   Author: alps-jbnu   File: problems.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def hot_problems(duration, limit):
    cache_key = 'hot_problems:%d:%d' % (duration.total_seconds(), limit)
    qs = cache.get(cache_key)
    if qs is None:
        qs = Problem.objects.filter(is_public=True, submission__date__gt=timezone.now() - duration, points__gt=3, points__lt=25)
        qs0 = qs.annotate(k=Count('submission__user', distinct=True)).order_by('-k').values_list('k', flat=True)
        
        if not qs0:
            return []
        # make this an aggregate
        mx = float(qs0[0])

        qs = qs.annotate(unique_user_count=Count('submission__user', distinct=True))  
        # fix braindamage in excluding CE  
        qs = qs.annotate(submission_volume=Count(Case(
                When(submission__result='AC', then=1),
                When(submission__result='WA', then=1),
                When(submission__result='IR', then=1),
                When(submission__result='RTE', then=1),
                When(submission__result='TLE', then=1),
                When(submission__result='OLE', then=1),
                output_field=FloatField(),
            )))
        qs = qs.annotate(ac_volume=Count(Case(
                When(submission__result='AC', then=1),
                output_field=FloatField(),
            )))
        qs = qs.filter(unique_user_count__gt=max(mx / 3.0, 1))

        qs = qs.annotate(ordering=ExpressionWrapper(0.5 * F('points') * (0.4 * F('ac_volume') / F('submission_volume') + 0.6 * F('ac_rate')) + 100 * e ** (F('unique_user_count') / mx), output_field=FloatField())).order_by('-ordering').defer('description')[:limit]

        cache.set(cache_key, qs, 900)
    return qs 
Example 41
Project: ShiftingBloomFilter   Author: hero24   File: shifting_bloom_filter.py    GNU General Public License v3.0 5 votes vote down vote up
def get_fpr(self):
        """
            (Number) returns false positve rate for current state
            of the filter
        """
        p = math.e ** ((-self.count * self.k)/len(self))
        fpr = ((1-p)**(self.k/2)) * (1 - p + (1/(self.max_set+1)) * (p**2))
        return fpr 
Example 42
Project: TCPJoker   Author: TCP-Joker-BOT   File: calc.py    MIT License 5 votes vote down vote up
def visit_List(self, node):
        return [self.visit(e) for e in node.elts] 
Example 43
Project: TCPJoker   Author: TCP-Joker-BOT   File: calc.py    MIT License 5 votes vote down vote up
def run(message):
    try:
        pool = multiprocessing.Pool(processes=1)
        async_result = pool.apply_async(Calc.evaluate, (message['text'].split(' ', 1)[1],), {})
        r = str(async_result.get(0.5))
        if len(r) > 100:
            return "Result too long"
        return r
    except ValueError as e:
        return "Error: {}".format(e)
    except (MemoryError, RuntimeError, SyntaxError):
        return "How kawaii!\nAre you trying to be a cute loli hacker? nyan~"
    except multiprocessing.context.TimeoutError:
        return "Evaluation timeout." 
Example 44
Project: Hierarchical-Meta-Reinforcement-Learning   Author: navneet-nmk   File: hyperparameter.py    MIT License 5 votes vote down vote up
def generate_next_value(self):
        return math.e ** (self._linear_float_param.generate()) + self.offset 
Example 45
Project: Hierarchical-Meta-Reinforcement-Learning   Author: navneet-nmk   File: hyperparameter.py    MIT License 5 votes vote down vote up
def generate_next_value(self):
        return int(
            math.e ** (self._linear_float_param.generate()) + self.offset
        ) 
Example 46
Project: rea   Author: tjanson   File: datastructures.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def __str__(self, *, head=True):
        if head:
            if self.graph.graph['type'] == 'probability':
                probability = math.e ** (-self.length)
                prefix = "Path [Prob: {:.3f}]: ".format(probability)
            else:
                prefix = "Path [Dist: {:.2f}]: ".format(self.length)
            return prefix + '"' + self.__str__(head=False) + '"'

        if self.tail is None:
            return "{}".format(self.head)
        else:
            tail_str = self.tail.__str__(head=False)
            tail_k_str = "[k={}]".format(self.tail_k) if self.tail_k is not None else ""
            return "{tail} {tail_k} -- {head}".format(tail=tail_str, tail_k=tail_k_str, head=self.head) 
Example 47
Project: parselglossy   Author: dev-cafe   File: test_standard.py    MIT License 5 votes vote down vote up
def keywords():
    stuff = contents().format(PI=math.pi, E=math.e, TAU=2.0 * math.pi)
    keys = """{CONTENTS}
"""
    return keys.format(CONTENTS=stuff) 
Example 48
Project: parselglossy   Author: dev-cafe   File: test_standard.py    MIT License 5 votes vote down vote up
def section(name):
    stuff = contents().format(PI=math.pi, E=math.e, TAU=2.0 * math.pi)
    sect = """{NAME} {{
    {CONTENTS}
}}
"""
    return sect.format(NAME=name, CONTENTS=stuff) 
Example 49
Project: parselglossy   Author: dev-cafe   File: test_standard.py    MIT License 5 votes vote down vote up
def flat_sections():
    stuff = contents().format(PI=math.pi, E=math.e, TAU=2.0 * math.pi)
    sects = """topsect {{
    {CONTENTS}
}}

foo<bar> {{
    {CONTENTS}
}}
"""
    return sects.format(CONTENTS=stuff) 
Example 50
Project: parselglossy   Author: dev-cafe   File: test_standard.py    MIT License 5 votes vote down vote up
def nested_sections():
    stuff = contents().format(PI=math.pi, E=math.e, TAU=2.0 * math.pi)
    sects = """topsect {{
    {CONTENTS}

    foo<bar> {{
        {CONTENTS}
    }}
}}
"""
    return sects.format(CONTENTS=stuff) 
Example 51
Project: parselglossy   Author: dev-cafe   File: test_standard.py    MIT License 5 votes vote down vote up
def keywords_and_section(name):
    stuff = contents().format(PI=math.pi, E=math.e, TAU=2.0 * math.pi)
    template = """/* This is a comment */
int = 42
// This is another comment
dbl = {PI}
cmplx = -1 -{E}*I
bool = on
str = "fooffa"

{NAME} {{
    {CONTENTS}
}}

! Yet another comment
$raw
H 0.0 0.0 0.0
F 1.0 1.0 1.0
$end

# I love comments!
int_array = [42]
dbl_array = [{PI}, {E}, {TAU}]
cmplx_array = [{PI} -2*j, {E}-2.0*J, {TAU}+1.5*i]
bool_array = [on, true, yes, False, True, false]
str_array = [foo, bar, "lorem", "IpSuM"]
"""
    inp = template.format(
        PI=math.pi, E=math.e, TAU=2.0 * math.pi, NAME=name, CONTENTS=stuff
    )
    return inp 
Example 52
Project: parselglossy   Author: dev-cafe   File: test_standard.py    MIT License 5 votes vote down vote up
def keywords_and_nested_sections():
    stuff = contents().format(PI=math.pi, E=math.e, TAU=2.0 * math.pi)
    template = """/* This is a comment */
int = 42
// This is another comment
dbl = {PI}
cmplx = -1 -{E}*I
bool = on
str = "fooffa"

! Yet another comment
$raw
H 0.0 0.0 0.0
F 1.0 1.0 1.0
$end

topsect {{
    {CONTENTS}

    foo<bar> {{
        {CONTENTS}
    }}
}}

# I love comments!
int_array = [42]
dbl_array = [{PI}, {E}, {TAU}]
cmplx_array = [{PI} -2*j, {E}-2.0*J, {TAU}+1.5*i]
bool_array = [on, true, yes, False, True, false]
str_array = [foo, bar, "lorem", "IpSuM"]
"""
    inp = template.format(PI=math.pi, E=math.e, TAU=2.0 * math.pi, CONTENTS=stuff)
    return inp 
Example 53
Project: parselglossy   Author: dev-cafe   File: test_getkw.py    MIT License 5 votes vote down vote up
def keywords():
    stuff = contents().format(PI=math.pi, E=math.e, TAU=2.0 * math.pi)
    keys = """{CONTENTS}
"""
    return keys.format(CONTENTS=stuff) 
Example 54
Project: parselglossy   Author: dev-cafe   File: test_getkw.py    MIT License 5 votes vote down vote up
def section(name):
    stuff = contents().format(PI=math.pi, E=math.e, TAU=2.0 * math.pi)
    sect = """{NAME} {{
    {CONTENTS}
}}
"""
    return sect.format(NAME=name, CONTENTS=stuff) 
Example 55
Project: parselglossy   Author: dev-cafe   File: test_getkw.py    MIT License 5 votes vote down vote up
def flat_sections():
    stuff = contents().format(PI=math.pi, E=math.e, TAU=2.0 * math.pi)
    sects = """topsect {{
    {CONTENTS}
}}

foo<bar> {{
    {CONTENTS}
}}
"""
    return sects.format(CONTENTS=stuff) 
Example 56
Project: parselglossy   Author: dev-cafe   File: test_getkw.py    MIT License 5 votes vote down vote up
def nested_sections():
    stuff = contents().format(PI=math.pi, E=math.e, TAU=2.0 * math.pi)
    sects = """topsect {{
    {CONTENTS}

    foo<bar> {{
        {CONTENTS}
    }}
}}
"""
    return sects.format(CONTENTS=stuff) 
Example 57
Project: parselglossy   Author: dev-cafe   File: test_getkw.py    MIT License 5 votes vote down vote up
def keywords_and_flat_sections():
    stuff = contents().format(PI=math.pi, E=math.e, TAU=2.0 * math.pi)
    template = """/* This is a comment */
int = 42
// This is another comment
dbl = {PI}
bool = on
str = "fooffa"

topsect {{
    {CONTENTS}
}}

! Yet another comment
$raw
H 0.0 0.0 0.0
F 1.0 1.0 1.0
$end

foo<bar> {{
    {CONTENTS}
}}

# I love comments!
int_array = [42]
dbl_array = [{PI}, {E}, {TAU}]
bool_array = [on, true, yes, False, True, false]
str_array = [foo, bar, "lorem", "IpSuM"]
"""
    inp = template.format(PI=math.pi, E=math.e, TAU=2.0 * math.pi, CONTENTS=stuff)
    return inp 
Example 58
Project: parselglossy   Author: dev-cafe   File: test_getkw.py    MIT License 5 votes vote down vote up
def keywords_and_nested_sections():
    stuff = contents().format(PI=math.pi, E=math.e, TAU=2.0 * math.pi)
    template = """/* This is a comment */
int = 42
// This is another comment
dbl = {PI}
bool = on
str = "fooffa"

! Yet another comment
$raw
H 0.0 0.0 0.0
F 1.0 1.0 1.0
$end

topsect {{
    {CONTENTS}

    foo<bar> {{
        {CONTENTS}
    }}
}}

# I love comments!
int_array = [42]
dbl_array = [{PI}, {E}, {TAU}]
bool_array = [on, true, yes, False, True, false]
str_array = [foo, bar, "lorem", "IpSuM"]
"""
    inp = template.format(PI=math.pi, E=math.e, TAU=2.0 * math.pi, CONTENTS=stuff)
    return inp 
Example 59
Project: 3DCT   Author: coraxx   File: beadPos.py    GNU General Public License v3.0 5 votes vote down vote up
def optimize_z(x,y,z,image,n=None):
	"""Optimize z for poly fit"""
	if type(image) == str:
		img = tf.imread(image)
	elif type(image) == np.ndarray:
		img = image

	data_z = img[:,y,x]

	if n is None:
		n = getn(data_z)

	x_opt_vals, y_opt_vals, z_opt_vals = [], [], []

	x_opt,y_opt,z_opt = x,y,z
	for i in range(5):
		try:
			print x_opt,y_opt,z_opt
			x_opt,y_opt,z_opt = int(round(x_opt)),int(round(y_opt)),int(round(z_opt))
			x_opt, y_opt = optimize_xy(x_opt,y_opt,z_opt,img,nx=None,ny=None)
			data_z = img[:,round(y_opt),round(x_opt)]
		except Exception as e:
			if clrmsg and debug is True: print clrmsg.ERROR
			print IndexError("Optimization failed, possibly due to low signal or low SNR. "+str(e))
			return [x],[y],['failed']
		n = getn(data_z)
		z_opt, data_z_yp_poly = parabolic.parabolic_polyfit(data_z, np.argmax(data_z), n)
		x_opt_vals.append(x_opt)
		y_opt_vals.append(y_opt)
		z_opt_vals.append(z_opt)

	return x_opt_vals, y_opt_vals, z_opt_vals 
Example 60
Project: 3DCT   Author: coraxx   File: beadPos.py    GNU General Public License v3.0 5 votes vote down vote up
def gaussfit(data,parent=None,hold=False):
	## Fitting gaussian to data
	data[1] = data[1]-data[1].min()
	p0 = [data[1].max(), data[1].argmax(), 1]
	popt, pcov = curve_fit(gauss, data[0], data[1], p0=p0)

	if parent is not None:
		## Draw graphs in GUI
		x = []
		y = []
		for i in np.arange(len(data[0])):
			x.append(i)
			y.append(gauss(i,*popt))
		if hold is False:
			parent.widget_matplotlib.setupScatterCanvas(width=4,height=4,dpi=52,toolbar=False)
		parent.widget_matplotlib.xyPlot(data[0], data[1], label='z data',clear=True)
		parent.widget_matplotlib.xyPlot(x, y, label='gaussian fit',clear=False)

	## DEBUG
	if clrmsg and debug is True:
		from scipy.stats import ks_2samp
		## Get std from the diagonal of the covariance matrix
		std_height, std_mean, std_sigma = np.sqrt(np.diag(pcov))
		print clrmsg.DEBUG + '='*15, 'GAUSS FIT', '='*25
		print clrmsg.DEBUG + 'Amplitude		:', popt[0]
		print clrmsg.DEBUG + 'Location		:', popt[1]
		## http://mathworld.wolfram.com/GaussianFunction.html -> sigma * 2 * sqrt(2 * ln(2))
		print clrmsg.DEBUG + 'FWHM			:', popt[2] * 2 * math.sqrt(2 * math.log(2,math.e))
		print clrmsg.DEBUG + 'Std. Amplitude	:', std_height
		print clrmsg.DEBUG + 'Std. Location	:', std_mean
		print clrmsg.DEBUG + 'Std. FWHM		:', std_sigma * 2 * math.sqrt(2 * math.log(2,math.e))
		print clrmsg.DEBUG + 'Mean dy		:', np.absolute(y-data[1]).mean()
		print clrmsg.DEBUG + str(ks_2samp(y, data[1]))
	return popt, pcov


## Gaussian 2D fit from http://scipy.github.io/old-wiki/pages/Cookbook/FittingData 
Example 61
Project: PySail-426   Author: j3b4   File: SimulazioneRegata300.py    GNU General Public License v3.0 5 votes vote down vote up
def DisegnaFincature(self):
        self.Graficodx.delete(ALL)
        #self.Graficosx.delete("icona")
        NW=self.Bbox[0]#angolo NW
        SE=self.Bbox[1]#angolo SE
        N=25
        height=float(self.Graficodx.cget("height"))
        width=float(self.Graficodx.cget("width"))
        Df=math.log(math.tan(SE[0]/2+math.pi/4)/math.tan(NW[0]/2+math.pi/4),math.e)
        self.q=math.copysign((NW[0]-SE[0])/Df,1)
        self.FattoreDiScala=0.85*min(height/math.copysign((NW[0]-SE[0]),1),width/(self.q*math.copysign((NW[1]-SE[1]),1)))
        lat=NW[0]
        passo=(NW[0]-SE[0])*1.0/N
        for i in range(0,N+1):
            self.disegna([(lat,NW[1]),(lat,SE[1])],"darkgray","fincature")#orizontali
            lat=lat-passo
        lon=NW[1]
        passo=(NW[1]-SE[1])*1.0/N
        for i in range(0,N+1):
            self.disegna([(NW[0],lon),(SE[0],lon)],"darkgray","fincature")#verticali
            lon=lon-passo
        testo=stampalat(NW[0])
        x=-NW[1]*self.FattoreDiScala*self.q
        y=-NW[0]*self.FattoreDiScala
        self.Graficodx.create_text(x-5,y-15,text=testo,fill="darkgray",tags="fincature",anchor="e", font=MIOFONT)
        testo=stampalon(NW[1])
        self.Graficodx.create_text(x-5,y,text=testo,fill="darkgray",tags="fincature",anchor="e", font=MIOFONT)
        testo=stampalat(SE[0])
        x=-SE[1]*self.FattoreDiScala*self.q
        y=-SE[0]*self.FattoreDiScala
        self.Graficodx.create_text(x+5,y,text=testo,fill="darkgray",tags="fincature",anchor="w", font=MIOFONT)
        testo=stampalon(SE[1])
        self.Graficodx.create_text(x+5,y+15,text=testo,fill="darkgray",tags="fincature",anchor="w", font=MIOFONT)
        x1=-self.Partenza[1]*self.FattoreDiScala*self.q
        y1=-self.Partenza[0]*self.FattoreDiScala
        self.Graficodx.create_rectangle(x1-3,y1-3,x1+3,y1+3,fill="red",tags="fincature")
        x2=-self.Arrivo[1]*self.FattoreDiScala*self.q
        y2=-self.Arrivo[0]*self.FattoreDiScala
        self.Graficodx.create_rectangle(x2-3,y2-3,x2+3,y2+3,fill="green",tags="fincature")
        self.Graficodx.create_line(x1,y1,x2,y2,fill=BGCOLOR,tags="fincature") 
Example 62
Project: PySail-426   Author: j3b4   File: SimulazioneRegata316.py    GNU General Public License v3.0 5 votes vote down vote up
def steerautomode(self,hdg=0.0):
        #calcola il TWA necessario a rispettare il modo di steer (modi gps,vmgwp e vmwtw)
        if self.mode=="compass":
            self.MaVie.TWA=riduci180(self.MaVie.TW[0]-hdg)
        if self.mode=="gps":
            self.MaVie.TWA=riduci180(self.MaVie.TW[0]-self.MaVie.BRGGPS(self.Arrivo))
        if self.mode=="vmgwp":
            self.MaVie.TWA=self.MaVie.TWAmaxVMGWP(self.Arrivo)
        if self.mode=="vmgtw":
            scarto=scartorotta(self.MaVie.TW[0],self.MaVie.BRG(self.Arrivo))
            if scarto<=math.pi/2:#poppa (mure a sx)
                TWA=self.MaVie.TWAmaxCMG(self.MaVie.TW[0])
            else:#bolina (mure a sx)
                TWA=self.MaVie.TWAmaxCMG(riduci360(self.MaVie.TW[0]+math.pi))
            #definire le mura
            '''
            hdgsx=riduci360(self.MaVie.TW[0]+TWA)#mure dx
            hdgdx=riduci360(self.MaVie.TW[0]-TWA)#mure sx
            brg=self.MaVie.BRG(self.Arrivo)
            if scartorotta(brg,hdgdx)<scartorotta(brg,hdgsx):
                TWA=-TWA
            self.MaVie.TWA=-TWA#twa positivi per mure a dritta
            '''
            self.MaVie.TWA=math.copysign(-TWA,self.MaVie.TWA)
        if self.mode=="cmg":
            try:
                ril=self.cmgtxt.get("1.0","1.end")
                ril=math.radians(int(ril))
                ril=riduci360(ril)
                self.MaVie.TWA=self.MaVie.TWAmaxCMG(ril)
            except:
                self.cmgtxt.delete("1.0",END) 
Example 63
Project: PySail-426   Author: j3b4   File: SimulazioneRegata316.py    GNU General Public License v3.0 5 votes vote down vote up
def CalcolaFattoreDiScala(self):
        NW=self.Bbox[0]#angolo NW
        SE=self.Bbox[1]#angolo SE
        height=float(self.Graficodx.cget("height"))
        width=float(self.Graficodx.cget("width"))
        Df=math.log(math.tan(SE[0]/2+math.pi/4)/math.tan(NW[0]/2+math.pi/4),math.e)
        self.q=math.copysign((NW[0]-SE[0])/Df,1)
        self.FattoreDiScala=0.85*min(height/math.copysign((NW[0]-SE[0]),1),width/(self.q*math.copysign((NW[1]-SE[1]),1))) 
Example 64
Project: PySail-426   Author: j3b4   File: SimulazioneRegata316.py    GNU General Public License v3.0 5 votes vote down vote up
def sigmoide(d,valore1,valore2,distanza,n=1):
    #n intero tra 1 (scalino marcato) e 6 (scalino dolce circa coseno)
    y=-10.0+20.0*d/distanza#y=[-10:10]
    y=y*1.0/n
    sigm=1.0*valore1+0.5*(valore2-valore1)*(1+math.tanh(y))
    grad_sigm=0.5*(valore2-valore1)/(math.cosh(y))**2
    grad_sigm=-grad_sigm*20.0/(n*distanza)
    return (sigm,grad_sigm)
#MAIN------------------------------------------------------------ 
Example 65
Project: PySail-426   Author: j3b4   File: ModuloNav.py    GNU General Public License v3.0 5 votes vote down vote up
def puntodistanterotta(latA,lonA,Distanza,Rotta):
    #non funziona in prossimita' dei poli
    #dove può risultare latC>90, log(tan(latC/...))=log(<0)   (*)
    a=Distanza*1.0/RaggioTerrestre
    latB=latA+a*math.cos(Rotta)
    if math.copysign(latA-latB,1)<=math.radians(0.1/3600.0):
        q=math.cos(latA)
    else:
        Df=math.log(math.tan(latB/2+math.pi/4)/math.tan(latA/2+math.pi/4),math.e)#(*)
        q=(latB-latA)/Df
    lonB=lonA-a*math.sin(Rotta)/q
    return latB,lonB 
Example 66
Project: PySail-426   Author: j3b4   File: ModuloNav.py    GNU General Public License v3.0 5 votes vote down vote up
def lossodromica(latA,lonA,latB,lonB):
    #non funziona in prossimita' dei poli
    #per latB=-90: math domain error log(0)
    #per latA=-90 [zero divison error]
    #per A==B ritorna (0.0,0.0)
    #if latA==latB:
    if  math.copysign(latA-latB,1)<=math.radians(0.1/3600.0):
        q=math.cos(latA)
    else:
        Df=math.log(math.tan(latB/2+math.pi/4)/math.tan(latA/2+math.pi/4),math.e)
        q=(latB-latA)*1.0/Df
    Distanza=RaggioTerrestre*((latA-latB)**2+(q*(lonA-lonB))**2)**0.5
    Rotta=math.atan2(-q*(lonB-lonA),(latB-latA))
    if Rotta<0:Rotta=Rotta+2.0*math.pi#atan2:[-pi,pi]
    return Distanza,Rotta 
Example 67
Project: PySail-426   Author: j3b4   File: SimulazioneRegata316.py    GNU General Public License v3.0 5 votes vote down vote up
def steerautomode(self,hdg=0.0):
        #calcola il TWA necessario a rispettare il modo di steer (modi gps,vmgwp e vmwtw)
        if self.mode=="compass":
            self.MaVie.TWA=riduci180(self.MaVie.TW[0]-hdg)
        if self.mode=="gps":
            self.MaVie.TWA=riduci180(self.MaVie.TW[0]-self.MaVie.BRGGPS(self.Arrivo))
        if self.mode=="vmgwp":
            self.MaVie.TWA=self.MaVie.TWAmaxVMGWP(self.Arrivo)
        if self.mode=="vmgtw":
            scarto=scartorotta(self.MaVie.TW[0],self.MaVie.BRG(self.Arrivo))
            if scarto<=math.pi/2:#poppa (mure a sx)
                TWA=self.MaVie.TWAmaxCMG(self.MaVie.TW[0])
            else:#bolina (mure a sx)
                TWA=self.MaVie.TWAmaxCMG(riduci360(self.MaVie.TW[0]+math.pi))
            #definire le mura
            '''
            hdgsx=riduci360(self.MaVie.TW[0]+TWA)#mure dx
            hdgdx=riduci360(self.MaVie.TW[0]-TWA)#mure sx
            brg=self.MaVie.BRG(self.Arrivo)
            if scartorotta(brg,hdgdx)<scartorotta(brg,hdgsx):
                TWA=-TWA
            self.MaVie.TWA=-TWA#twa positivi per mure a dritta
            '''
            self.MaVie.TWA=math.copysign(-TWA,self.MaVie.TWA)
        if self.mode=="cmg":
            try:
                ril=self.cmgtxt.get("1.0","1.end")
                ril=math.radians(int(ril))
                ril=riduci360(ril)
                self.MaVie.TWA=self.MaVie.TWAmaxCMG(ril)
            except:
                self.cmgtxt.delete("1.0",END) 
Example 68
Project: PySail-426   Author: j3b4   File: SimulazioneRegata316.py    GNU General Public License v3.0 5 votes vote down vote up
def CalcolaFattoreDiScala(self):
        NW=self.Bbox[0]#angolo NW
        SE=self.Bbox[1]#angolo SE
        height=float(self.Graficodx.cget("height"))
        width=float(self.Graficodx.cget("width"))
        Df=math.log(math.tan(SE[0]/2+math.pi/4)/math.tan(NW[0]/2+math.pi/4),math.e)
        self.q=math.copysign((NW[0]-SE[0])/Df,1)
        self.FattoreDiScala=0.85*min(height/math.copysign((NW[0]-SE[0]),1),width/(self.q*math.copysign((NW[1]-SE[1]),1))) 
Example 69
Project: PySail-426   Author: j3b4   File: SimulazioneRegata316.py    GNU General Public License v3.0 5 votes vote down vote up
def DisegnaFincature(self):
        #self.Graficodx.delete(ALL)
        self.Graficodx.delete("fincature")
        NW=self.Bbox[0]#angolo NW
        SE=self.Bbox[1]#angolo SE
        N=25
        lat=NW[0]
        passo=(NW[0]-SE[0])*1.0/N
        for i in range(0,N+1):
            self.disegna([(lat,NW[1]),(lat,SE[1])],"darkgray","fincature")#orizontali
            lat=lat-passo
        lon=NW[1]
        passo=(NW[1]-SE[1])*1.0/N
        for i in range(0,N+1):
            self.disegna([(NW[0],lon),(SE[0],lon)],"darkgray","fincature")#verticali
            lon=lon-passo
        testo=stampalat(NW[0])
        x=-NW[1]*self.FattoreDiScala*self.q
        y=-NW[0]*self.FattoreDiScala
        self.Graficodx.create_text(x-5,y-15,text=testo,fill="darkgray",tags="fincature",anchor="e", font=MIOFONT)
        testo=stampalon(NW[1])
        self.Graficodx.create_text(x-5,y,text=testo,fill="darkgray",tags="fincature",anchor="e", font=MIOFONT)
        testo=stampalat(SE[0])
        x=-SE[1]*self.FattoreDiScala*self.q
        y=-SE[0]*self.FattoreDiScala
        self.Graficodx.create_text(x+5,y,text=testo,fill="darkgray",tags="fincature",anchor="w", font=MIOFONT)
        testo=stampalon(SE[1])
        self.Graficodx.create_text(x+5,y+15,text=testo,fill="darkgray",tags="fincature",anchor="w", font=MIOFONT)
        x1=-self.Partenza[1]*self.FattoreDiScala*self.q
        y1=-self.Partenza[0]*self.FattoreDiScala
        self.Graficodx.create_rectangle(x1-3,y1-3,x1+3,y1+3,fill="red",tags="fincature")
        x2=-self.Arrivo[1]*self.FattoreDiScala*self.q
        y2=-self.Arrivo[0]*self.FattoreDiScala
        self.Graficodx.create_rectangle(x2-3,y2-3,x2+3,y2+3,fill="green",tags="fincature")
        self.Graficodx.create_line(x1,y1,x2,y2,fill=BGCOLOR,tags="fincature") 
Example 70
Project: rpython-lang-scheme   Author: tomoh1r   File: rcomplex.py    MIT License 5 votes vote down vote up
def c_exp(x, y):
    if not isfinite(x) or not isfinite(y):
        if isinf(x) and isfinite(y) and y != 0.:
            if x > 0:
                real = copysign(INF, math.cos(y))
                imag = copysign(INF, math.sin(y))
            else:
                real = copysign(0., math.cos(y))
                imag = copysign(0., math.sin(y))
            r = (real, imag)
        else:
            r = exp_special_values[special_type(x)][special_type(y)]

        # need to raise ValueError if y is +/- infinity and x is not
        # a NaN and not -infinity
        if isinf(y) and (isfinite(x) or (isinf(x) and x > 0)):
            raise ValueError("math domain error")
        return r

    if x > CM_LOG_LARGE_DOUBLE:
        l = math.exp(x-1.)
        real = l * math.cos(y) * math.e
        imag = l * math.sin(y) * math.e
    else:
        l = math.exp(x)
        real = l * math.cos(y)
        imag = l * math.sin(y)
    if isinf(real) or isinf(imag):
        raise OverflowError("math range error")
    return real, imag 
Example 71
Project: rpython-lang-scheme   Author: tomoh1r   File: rcomplex.py    MIT License 5 votes vote down vote up
def c_cosh(x, y):
    if not isfinite(x) or not isfinite(y):
        if isinf(x) and isfinite(y) and y != 0.:
            if x > 0:
                real = copysign(INF, math.cos(y))
                imag = copysign(INF, math.sin(y))
            else:
                real = copysign(INF, math.cos(y))
                imag = -copysign(INF, math.sin(y))
            r = (real, imag)
        else:
            r = cosh_special_values[special_type(x)][special_type(y)]

        # need to raise ValueError if y is +/- infinity and x is not
        # a NaN
        if isinf(y) and not isnan(x):
            raise ValueError("math domain error")
        return r

    if fabs(x) > CM_LOG_LARGE_DOUBLE:
        # deal correctly with cases where cosh(x) overflows but
        # cosh(z) does not.
        x_minus_one = x - copysign(1., x)
        real = math.cos(y) * math.cosh(x_minus_one) * math.e
        imag = math.sin(y) * math.sinh(x_minus_one) * math.e
    else:
        real = math.cos(y) * math.cosh(x)
        imag = math.sin(y) * math.sinh(x)
    if isinf(real) or isinf(imag):
        raise OverflowError("math range error")
    return real, imag 
Example 72
Project: rpython-lang-scheme   Author: tomoh1r   File: rcomplex.py    MIT License 5 votes vote down vote up
def c_sinh(x, y):
    # special treatment for sinh(+/-inf + iy) if y is finite and nonzero
    if not isfinite(x) or not isfinite(y):
        if isinf(x) and isfinite(y) and y != 0.:
            if x > 0:
                real = copysign(INF, math.cos(y))
                imag = copysign(INF, math.sin(y))
            else:
                real = -copysign(INF, math.cos(y))
                imag = copysign(INF, math.sin(y))
            r = (real, imag)
        else:
            r = sinh_special_values[special_type(x)][special_type(y)]

        # need to raise ValueError if y is +/- infinity and x is not
        # a NaN
        if isinf(y) and not isnan(x):
            raise ValueError("math domain error")
        return r

    if fabs(x) > CM_LOG_LARGE_DOUBLE:
        x_minus_one = x - copysign(1., x)
        real = math.cos(y) * math.sinh(x_minus_one) * math.e
        imag = math.sin(y) * math.cosh(x_minus_one) * math.e
    else:
        real = math.cos(y) * math.sinh(x)
        imag = math.sin(y) * math.cosh(x)
    if isinf(real) or isinf(imag):
        raise OverflowError("math range error")
    return real, imag 
Example 73
Project: rpython-lang-scheme   Author: tomoh1r   File: test_rbigint.py    MIT License 5 votes vote down vote up
def test_log(self):
        from rpython.rlib.rfloat import ulps_check
        for op in long_vals:
            if not op:
                continue
            for base in [0, 2, 4, 8, 16, 10, math.e]:
                l = rbigint.fromlong(op).log(base)
                if base:
                    assert ulps_check(l, math.log(op, base)) is None
                else:
                    assert ulps_check(l, math.log(op)) is None 
Example 74
Project: ironpython2   Author: IronLanguages   File: test_callbacks.py    Apache License 2.0 5 votes vote down vote up
def test_float(self):
        # only almost equal: double -> float -> double
        import math
        self.check_type(c_float, math.e)
        self.check_type(c_float, -math.e) 
Example 75
Project: ironpython2   Author: IronLanguages   File: test_callbacks.py    Apache License 2.0 5 votes vote down vote up
def test_callback_register_int(self):
        # Issue #8275: buggy handling of callback args under Win64
        # NOTE: should be run on release builds as well
        dll = CDLL(_ctypes_test.__file__)
        CALLBACK = CFUNCTYPE(c_int, c_int, c_int, c_int, c_int, c_int)
        # All this function does is call the callback with its args squared
        func = dll._testfunc_cbk_reg_int
        func.argtypes = (c_int, c_int, c_int, c_int, c_int, CALLBACK)
        func.restype = c_int

        def callback(a, b, c, d, e):
            return a + b + c + d + e

        result = func(2, 3, 4, 5, 6, CALLBACK(callback))
        self.assertEqual(result, callback(2*2, 3*3, 4*4, 5*5, 6*6)) 
Example 76
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 4 votes vote down vote up
def result_check(expected, got, ulp_tol=5, abs_tol=0.0):
    # Common logic of MathTests.(ftest, test_testcases, test_mtestcases)
    """Compare arguments expected and got, as floats, if either
    is a float, using a tolerance expressed in multiples of
    ulp(expected) or absolutely (if given and greater).

    As a convenience, when neither argument is a float, and for
    non-finite floats, exact equality is demanded. Also, nan==nan
    as far as this function is concerned.

    Returns None on success and an error message on failure.
    """

    # Check exactly equal (applies also to strings representing exceptions)
    if got == expected:
        return None

    failure = "not equal"

    # Turn mixed float and int comparison (e.g. floor()) to all-float
    if isinstance(expected, float) and isinstance(got, int):
        got = float(got)
    elif isinstance(got, float) and isinstance(expected, int):
        expected = float(expected)

    if isinstance(expected, float) and isinstance(got, float):
        if math.isnan(expected) and math.isnan(got):
            # Pass, since both nan
            failure = None
        elif math.isinf(expected) or math.isinf(got):
            # We already know they're not equal, drop through to failure
            pass
        else:
            # Both are finite floats (now). Are they close enough?
            failure = ulp_abs_check(expected, got, ulp_tol, abs_tol)

    # arguments are not equal, and if numeric, are too far apart
    if failure is not None:
        fail_fmt = "expected {!r}, got {!r}"
        fail_msg = fail_fmt.format(expected, got)
        fail_msg += ' ({})'.format(failure)
        return fail_msg
    else:
        return None

# Class providing an __index__ method. 
Example 77
Project: PySail-426   Author: j3b4   File: SimulazioneRegata300.py    GNU General Public License v3.0 4 votes vote down vote up
def SettaStrVar(self):
        #metodo chiamato dall'evento Play e dai metodi inizia e RafficaUtility 
        if self.MaVie.TWA>=0:
            self.TWA_strvar.set("%3.0f"%math.degrees(self.MaVie.TWA)+u"°-")
        else:
            self.TWA_strvar.set("%3.0f"%math.degrees(self.MaVie.TWA)+u"°")
        self.TWD_strvar.set("%3.0f"%math.degrees(self.MaVie.TW[0])+u"°")
        self.TWS_strvar.set("%3.1f"%self.MaVie.TW[1]+"knt")
        self.VMGTWD_strvar.set("%3.2f"%self.MaVie.VMGTWD()+"knts")
        hdg=self.MaVie.HDG()
        speed=self.MaVie.Speed()
        brg=self.MaVie.BRG(self.Arrivo)
        dist=self.MaVie.Dist(self.Arrivo)
        #if brg<>"nd":#caso dell'arrivo
        if dist>0:
            scarto=scartorotta(brg,self.Course[1])
            x=dist*math.cos(scarto)
            y=dist*math.sin(scarto)
            self.BRG_strvar.set("%3.0f"%math.degrees(brg)+u"°")
            self.Dist_strvar.set("%3.1f"%dist+"nm")
            self.VMGBRG_strvar.set("%3.2f"%self.MaVie.VMGWP(self.Arrivo)+"knts")
            self.Dist_strvar.set("%3.1f"%dist+"nm")
            self.XCourse_strvar.set("%3.1f"%x+"nm")
            self.YCourse_strvar.set("%3.1f"%y+"nm")
        else:#arrivo
            self.BRG_strvar.set(u"nd°")
            self.VMGBRG_strvar.set("0.00knts")
            self.XCourse_strvar.set("0.00nm")
            self.YCourse_strvar.set("0.00nm")
        self.VMGCourse_strvar.set("%3.2f"%self.MaVie.CMG(self.Course[1])+"knts")
        self.HDG_strvar.set("%3.0f"%math.degrees(hdg)+u"°")
        self.Speed_strvar.set("%3.2f"%speed+"knts")
        self.Log_strvar.set("%3.2f"%self.MaVie.Log+"nm")
        self.Dist_strvar.set("%3.1f"%dist+"nm")
        self.Lat_strvar.set(self.MaVie.StampaLat())
        self.Lon_strvar.set(self.MaVie.StampaLon())
        self.T_strvar.set(stampatempo(self.T))
        #aggiorna tracking        
        trackinfo=self.T_strvar.get()+"\t"
        trackinfo=trackinfo+self.TWD_strvar.get()+"\t"
        trackinfo=trackinfo+self.TWS_strvar.get()+"\t"
        trackinfo=trackinfo+self.TWA_strvar.get()+"\t"
        trackinfo=trackinfo+self.HDG_strvar.get()+"\t"
        trackinfo=trackinfo+self.Speed_strvar.get()+"\t"
        trackinfo=trackinfo+self.Log_strvar.get()+"\t"
        trackinfo=trackinfo+self.BRG_strvar.get()+"\t"
        trackinfo=trackinfo+self.Dist_strvar.get()+"\t"
        trackinfo=trackinfo+self.Lat_strvar.get()+"\t"
        trackinfo=trackinfo+self.Lon_strvar.get()+"\t"
        trackinfo=trackinfo+self.XCourse_strvar.get()+"\t"
        trackinfo=trackinfo+self.YCourse_strvar.get()+"\t"
        trackinfo=trackinfo+self.VMGTWD_strvar.get()+"\t"
        trackinfo=trackinfo+self.VMGBRG_strvar.get()+"\t"
        trackinfo=trackinfo+self.VMGCourse_strvar.get()+"\n"
        self.Track.config(state=NORMAL)
        self.Track.insert(2.0,trackinfo)
        self.Track.config(state=DISABLED)
        
        self.SettaBottoni() 
Example 78
Project: PySail-426   Author: j3b4   File: SimulazioneRegata316.py    GNU General Public License v3.0 4 votes vote down vote up
def SettaStrVar(self):
        #metodo chiamato dall'evento Step e dai metodi inizia e RafficaUtility 
        if self.MaVie.TWA>=0:
            self.TWA_strvar.set("%3.0f"%math.degrees(self.MaVie.TWA)+u"°-")
        else:
            self.TWA_strvar.set("%3.0f"%math.degrees(self.MaVie.TWA)+u"°")
        self.TWD_strvar.set("%3.0f"%math.degrees(self.MaVie.TW[0])+u"°")
        self.TWS_strvar.set("%3.1f"%self.MaVie.TW[1]+"knt")
        self.VMGTWD_strvar.set("%3.2f"%self.MaVie.VMGTWD()+"knts")
        hdg=self.MaVie.HDG()
        speed=self.MaVie.Speed()
        brg=self.MaVie.BRG(self.Arrivo)
        dist=self.MaVie.Dist(self.Arrivo)
        #if brg<>"nd":#caso dell'arrivo
        if dist>0:
            scarto=scartorotta(brg,self.Course[1])
            x=dist*math.cos(scarto)
            y=dist*math.sin(scarto)
            self.BRG_strvar.set("%3.0f"%math.degrees(brg)+u"°")
            self.Dist_strvar.set("%3.1f"%dist+"nm")
            self.VMGBRG_strvar.set("%3.2f"%self.MaVie.VMGWP(self.Arrivo)+"knts")
            self.Dist_strvar.set("%3.1f"%dist+"nm")
            self.XCourse_strvar.set("%3.1f"%x+"nm")
            self.YCourse_strvar.set("%3.1f"%y+"nm")
        else:#arrivo
            self.BRG_strvar.set(u"nd°")
            self.VMGBRG_strvar.set("0.00knts")
            self.XCourse_strvar.set("0.00nm")
            self.YCourse_strvar.set("0.00nm")
        self.VMGCourse_strvar.set("%3.2f"%self.MaVie.CMG(self.Course[1])+"knts")
        self.HDG_strvar.set("%3.0f"%math.degrees(hdg)+u"°")
        self.Speed_strvar.set("%3.2f"%speed+"knts")
        self.Log_strvar.set("%3.2f"%self.MaVie.Log+"nm")
        self.Dist_strvar.set("%3.1f"%dist+"nm")
        self.Lat_strvar.set(self.MaVie.StampaLat())
        self.Lon_strvar.set(self.MaVie.StampaLon())
        self.T_strvar.set(stampatempo(self.T))
        #aggiorna tracking        
        trackinfo=self.T_strvar.get()+"\t"
        trackinfo=trackinfo+self.TWD_strvar.get()+"\t"
        trackinfo=trackinfo+self.TWS_strvar.get()+"\t"
        trackinfo=trackinfo+self.TWA_strvar.get()+"\t"
        trackinfo=trackinfo+self.HDG_strvar.get()+"\t"
        trackinfo=trackinfo+self.Speed_strvar.get()+"\t"
        trackinfo=trackinfo+self.Log_strvar.get()+"\t"
        trackinfo=trackinfo+self.BRG_strvar.get()+"\t"
        trackinfo=trackinfo+self.Dist_strvar.get()+"\t"
        trackinfo=trackinfo+self.Lat_strvar.get()+"\t"
        trackinfo=trackinfo+self.Lon_strvar.get()+"\t"
        trackinfo=trackinfo+self.XCourse_strvar.get()+"\t"
        trackinfo=trackinfo+self.YCourse_strvar.get()+"\t"
        trackinfo=trackinfo+self.VMGTWD_strvar.get()+"\t"
        trackinfo=trackinfo+self.VMGBRG_strvar.get()+"\t"
        trackinfo=trackinfo+self.VMGCourse_strvar.get()+"\n"
        self.Track.config(state=NORMAL)
        self.Track.insert(2.0,trackinfo)
        self.Track.config(state=DISABLED)
        #self.SettaBottoni() 
Example 79
Project: PySail-426   Author: j3b4   File: SimulazioneRegata316.py    GNU General Public License v3.0 4 votes vote down vote up
def SettaStrVar(self):
        #metodo chiamato dall'evento Step e dai metodi inizia e RafficaUtility 
        if self.MaVie.TWA>=0:
            self.TWA_strvar.set("%3.0f"%math.degrees(self.MaVie.TWA)+u"°-")
        else:
            self.TWA_strvar.set("%3.0f"%math.degrees(self.MaVie.TWA)+u"°")
        self.TWD_strvar.set("%3.0f"%math.degrees(self.MaVie.TW[0])+u"°")
        self.TWS_strvar.set("%3.1f"%self.MaVie.TW[1]+"knt")
        self.VMGTWD_strvar.set("%3.2f"%self.MaVie.VMGTWD()+"knts")
        hdg=self.MaVie.HDG()
        speed=self.MaVie.Speed()
        brg=self.MaVie.BRG(self.Arrivo)
        dist=self.MaVie.Dist(self.Arrivo)
        #if brg<>"nd":#caso dell'arrivo
        if dist>0:
            scarto=scartorotta(brg,self.Course[1])
            x=dist*math.cos(scarto)
            y=dist*math.sin(scarto)
            self.BRG_strvar.set("%3.0f"%math.degrees(brg)+u"°")
            self.Dist_strvar.set("%3.1f"%dist+"nm")
            self.VMGBRG_strvar.set("%3.2f"%self.MaVie.VMGWP(self.Arrivo)+"knts")
            self.Dist_strvar.set("%3.1f"%dist+"nm")
            self.XCourse_strvar.set("%3.1f"%x+"nm")
            self.YCourse_strvar.set("%3.1f"%y+"nm")
        else:#arrivo
            self.BRG_strvar.set(u"nd°")
            self.VMGBRG_strvar.set("0.00knts")
            self.XCourse_strvar.set("0.00nm")
            self.YCourse_strvar.set("0.00nm")
        self.VMGCourse_strvar.set("%3.2f"%self.MaVie.CMG(self.Course[1])+"knts")
        self.HDG_strvar.set("%3.0f"%math.degrees(hdg)+u"°")
        self.Speed_strvar.set("%3.2f"%speed+"knts")
        self.Log_strvar.set("%3.2f"%self.MaVie.Log+"nm")
        self.Dist_strvar.set("%3.1f"%dist+"nm")
        self.Lat_strvar.set(self.MaVie.StampaLat())
        self.Lon_strvar.set(self.MaVie.StampaLon())
        self.T_strvar.set(stampatempo(self.T))
        #aggiorna tracking        
        trackinfo=self.T_strvar.get()+"\t"
        trackinfo=trackinfo+self.TWD_strvar.get()+"\t"
        trackinfo=trackinfo+self.TWS_strvar.get()+"\t"
        trackinfo=trackinfo+self.TWA_strvar.get()+"\t"
        trackinfo=trackinfo+self.HDG_strvar.get()+"\t"
        trackinfo=trackinfo+self.Speed_strvar.get()+"\t"
        trackinfo=trackinfo+self.Log_strvar.get()+"\t"
        trackinfo=trackinfo+self.BRG_strvar.get()+"\t"
        trackinfo=trackinfo+self.Dist_strvar.get()+"\t"
        trackinfo=trackinfo+self.Lat_strvar.get()+"\t"
        trackinfo=trackinfo+self.Lon_strvar.get()+"\t"
        trackinfo=trackinfo+self.XCourse_strvar.get()+"\t"
        trackinfo=trackinfo+self.YCourse_strvar.get()+"\t"
        trackinfo=trackinfo+self.VMGTWD_strvar.get()+"\t"
        trackinfo=trackinfo+self.VMGBRG_strvar.get()+"\t"
        trackinfo=trackinfo+self.VMGCourse_strvar.get()+"\n"
        self.Track.config(state=NORMAL)
        self.Track.insert(2.0,trackinfo)
        self.Track.config(state=DISABLED)
        #self.SettaBottoni() 
Example 80
Project: rpython-lang-scheme   Author: tomoh1r   File: rcomplex.py    MIT License 4 votes vote down vote up
def c_log(x, y):
    # The usual formula for the real part is log(hypot(z.real, z.imag)).
    # There are four situations where this formula is potentially
    # problematic:
    #
    # (1) the absolute value of z is subnormal.  Then hypot is subnormal,
    # so has fewer than the usual number of bits of accuracy, hence may
    # have large relative error.  This then gives a large absolute error
    # in the log.  This can be solved by rescaling z by a suitable power
    # of 2.
    #
    # (2) the absolute value of z is greater than DBL_MAX (e.g. when both
    # z.real and z.imag are within a factor of 1/sqrt(2) of DBL_MAX)
    # Again, rescaling solves this.
    #
    # (3) the absolute value of z is close to 1.  In this case it's
    # difficult to achieve good accuracy, at least in part because a
    # change of 1ulp in the real or imaginary part of z can result in a
    # change of billions of ulps in the correctly rounded answer.
    #
    # (4) z = 0.  The simplest thing to do here is to call the
    # floating-point log with an argument of 0, and let its behaviour
    # (returning -infinity, signaling a floating-point exception, setting
    # errno, or whatever) determine that of c_log.  So the usual formula
    # is fine here.

    # XXX the following two lines seem unnecessary at least on Linux;
    # the tests pass fine without them
    if not isfinite(x) or not isfinite(y):
        return log_special_values[special_type(x)][special_type(y)]

    ax = fabs(x)
    ay = fabs(y)

    if ax > CM_LARGE_DOUBLE or ay > CM_LARGE_DOUBLE:
        real = math.log(math.hypot(ax/2., ay/2.)) + M_LN2
    elif ax < DBL_MIN and ay < DBL_MIN:
        if ax > 0. or ay > 0.:
            # catch cases where hypot(ax, ay) is subnormal
            real = math.log(math.hypot(math.ldexp(ax, DBL_MANT_DIG),
                                       math.ldexp(ay, DBL_MANT_DIG)))
            real -= DBL_MANT_DIG*M_LN2
        else:
            # log(+/-0. +/- 0i)
            raise ValueError("math domain error")
            #real = -INF
            #imag = atan2(y, x)
    else:
        h = math.hypot(ax, ay)
        if 0.71 <= h and h <= 1.73:
            am = max(ax, ay)
            an = min(ax, ay)
            real = log1p((am-1)*(am+1) + an*an) / 2.
        else:
            real = math.log(h)
    imag = math.atan2(y, x)
    return (real, imag)