• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python math.isclose函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中math.isclose函数的典型用法代码示例。如果您正苦于以下问题:Python isclose函数的具体用法?Python isclose怎么用?Python isclose使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了isclose函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_convert_to_square_resolution

def test_convert_to_square_resolution(renderer, spoof_tesseract_cache,
                                      resources, outpdf):
    from math import isclose

    # Confirm input image is non-square resolution
    in_pageinfo = PdfInfo(resources / 'aspect.pdf')
    assert in_pageinfo[0].xres != in_pageinfo[0].yres

    # --force-ocr requires means forced conversion to square resolution
    check_ocrmypdf(
        resources / 'aspect.pdf', outpdf,
        '--force-ocr',
        '--pdf-renderer', renderer, env=spoof_tesseract_cache)

    out_pageinfo = PdfInfo(outpdf)

    in_p0, out_p0 = in_pageinfo[0], out_pageinfo[0]

    # Resolution show now be equal
    assert out_p0.xres == out_p0.yres

    # Page size should match input page size
    assert isclose(in_p0.width_inches,
                   out_p0.width_inches)
    assert isclose(in_p0.height_inches,
                   out_p0.height_inches)

    # Because we rasterized the page to produce a new image, it should occupy
    # the entire page
    out_im_w = out_p0.images[0]['width'] / out_p0.images[0]['dpi_w']
    out_im_h = out_p0.images[0]['height'] / out_p0.images[0]['dpi_h']
    assert isclose(out_p0.width_inches, out_im_w)
    assert isclose(out_p0.height_inches, out_im_h)
开发者ID:stweil,项目名称:OCRmyPDF,代码行数:33,代码来源:test_main.py


示例2: test_rgbled_pulse_background

def test_rgbled_pulse_background():
    r, g, b = (Device.pin_factory.pin(i) for i in (4, 5, 6))
    with RGBLED(1, 2, 3) as led:
        start = time()
        led.pulse(0.2, 0.2, n=2)
        assert isclose(time() - start, 0, abs_tol=0.05)
        led._blink_thread.join()
        assert isclose(time() - start, 0.8, abs_tol=0.05)
        expected = [
            (0.0, 0),
            (0.04, 0.2),
            (0.04, 0.4),
            (0.04, 0.6),
            (0.04, 0.8),
            (0.04, 1),
            (0.04, 0.8),
            (0.04, 0.6),
            (0.04, 0.4),
            (0.04, 0.2),
            (0.04, 0),
            (0.04, 0.2),
            (0.04, 0.4),
            (0.04, 0.6),
            (0.04, 0.8),
            (0.04, 1),
            (0.04, 0.8),
            (0.04, 0.6),
            (0.04, 0.4),
            (0.04, 0.2),
            (0.04, 0),
            ]
        r.assert_states_and_times(expected)
        g.assert_states_and_times(expected)
        b.assert_states_and_times(expected)
开发者ID:SteveAmor,项目名称:python-gpiozero,代码行数:34,代码来源:test_outputs.py


示例3: list_to_monolists_concat

def list_to_monolists_concat(lis, key=lambda x: x):
    """
    list_to_monolists and concatenates at stationary key.
    >>> pairs = [(0, 0), (1, 1),
    ...          (1, 2), (0, 3), (0, 4), (-1, 5),
    ...          (-1, 6), (0, 7),
    ...          (0, 8), (10, 9)]
    >>> list_to_monolists(pairs, key=lambda x: x[0])
    ... # doctest: +NORMALIZE_WHITESPACE
    ([[(0, 0), (1, 1)],
      [(1, 2), (0, 3)],
      [(0, 4), (-1, 5)],
      [(-1, 6), (0, 7)],
      [(0, 8), (10, 9)]],
     [1, -1, -1, 1, 10])

    >>> list_to_monolists_concat(pairs, key=lambda x: x[0])
    ... # doctest: +NORMALIZE_WHITESPACE
    ([[(0, 0), (1, 1)],
      [(1, 2), (0, 3), (-1, 5)],
      [(-1, 6), (0, 7)],
      [(0, 8), (10, 9)]],
      [1, -1, 1, 10])
    """
    lists, diffs = list_to_monolists(lis, key)
    for i in range(len(diffs) - 2, -1, -1):  # Second from last --> 0
        key1 = key(lists[i][-1])
        key2 = key(lists[i + 1][0])
        if math.isclose(diffs[i], diffs[i + 1]) and math.isclose(key1, key2):
            del diffs[i + 1]
            del lists[i + 1][0]
            lists[i] += lists[i + 1]
            del lists[i + 1]
    return lists, diffs
开发者ID:wataash,项目名称:instr,代码行数:34,代码来源:algorithms.py


示例4: request

    def request(self, layer, crs, style, dotiming=False, checkimg=False,
                saveimg=False, profiler=None):
        """Requests WMS image from server and returns image"""
        env = self.base_env.copy()
        query = self.base_query_map.copy()
        bounds = list(self.wms[layer].boundingBoxWGS84)
        if crs != 'EPSG:4326':
            delta = 1.0 # We move 1 degrees away from the poles
            if math.isclose(bounds[1], -90.0):
                bounds[1] += delta
            if math.isclose(bounds[3], 90.0):
                bounds[3] -= delta
        bbox = wms_utils.get_bounding_box(bounds, crs)
        if bbox != '':
            query['BBOX'] = bbox
        query['CRS'] = crs
    
        t = self.wms[layer].timepositions
        if t is not None:
            t = [tv.strip() for tv in t]
            query['TIME'] = t[int(len(t)/2)]

        elevations = self.wms[layer].elevations
        if elevations is not None:
            elevations = [ev.strip() for ev in elevations]
            query['ELEVATION'] = elevations[int(len(elevations)/2)]

        query['LAYERS'] = layer
        query['STYLES'] = style

        t = None
        if dotiming:
            t1 = time.clock()
        if profiler is not None:
            profiler.enable()
        response = self.get(params=query,
                            extra_environ=self.base_env, status=200)
        result = response.body[:]

        if profiler is not None:
            profiler.disable()
        if dotiming:
            t2 = time.clock()
            t = (t2-t1)*1000
        if saveimg:
            with open('tmp/png_%s_%s.png' % (layer, crs), 'wb') as f:
                f.write(result)
        if checkimg:
            is_blank = wms_utils.check_blank(result)
            if is_blank:
                # Construct URL for easy testing in browser
                url = self.path_info + '?' + urllib.parse.urlencode(query)
                msg = "Error: Blank image returned for layer=%s; crs=%s" % (layer, crs)
                msg += "\nQuery: " + url
                raise SystemExit(msg)
                """
            else:
                print('Image data seems OK')
                """
        return result, t
开发者ID:jblarsen,项目名称:pydap.responses.wms,代码行数:60,代码来源:test_wms.py


示例5: test_output_pwm_fade_background

def test_output_pwm_fade_background():
    pin = Device.pin_factory.pin(4)
    with PWMOutputDevice(4) as device:
        start = time()
        device.blink(0, 0, 0.2, 0.2, n=2)
        assert isclose(time() - start, 0, abs_tol=0.05)
        device._blink_thread.join()
        assert isclose(time() - start, 0.8, abs_tol=0.05)
        pin.assert_states_and_times([
            (0.0, 0),
            (0.04, 0.2),
            (0.04, 0.4),
            (0.04, 0.6),
            (0.04, 0.8),
            (0.04, 1),
            (0.04, 0.8),
            (0.04, 0.6),
            (0.04, 0.4),
            (0.04, 0.2),
            (0.04, 0),
            (0.04, 0.2),
            (0.04, 0.4),
            (0.04, 0.6),
            (0.04, 0.8),
            (0.04, 1),
            (0.04, 0.8),
            (0.04, 0.6),
            (0.04, 0.4),
            (0.04, 0.2),
            (0.04, 0),
            ])
开发者ID:SteveAmor,项目名称:python-gpiozero,代码行数:31,代码来源:test_outputs.py


示例6: test_single_page_image

def test_single_page_image(outdir):
    filename = outdir / 'image-mono.pdf'

    im_tmp = outdir / 'tmp.png'
    im = Image.new('1', (8, 8), 0)
    for n in range(8):
        im.putpixel((n, n), 1)
    im.save(str(im_tmp), format='PNG')

    imgsize = ((img2pdf.ImgSize.dpi, 8), (img2pdf.ImgSize.dpi, 8))
    layout_fun = img2pdf.get_layout_fun(None, imgsize, None, None, None)

    im_bytes = im_tmp.read_bytes()
    pdf_bytes = img2pdf.convert(
            im_bytes, producer="img2pdf", with_pdfrw=False,
            layout_fun=layout_fun)
    filename.write_bytes(pdf_bytes)

    info = pdfinfo.PdfInfo(filename)

    assert len(info) == 1
    page = info[0]

    assert not page.has_text
    assert len(page.images) == 1

    pdfimage = page.images[0]
    assert pdfimage.width == 8
    assert pdfimage.color == Colorspace.gray

    # DPI in a 1"x1" is the image width
    assert isclose(pdfimage.xres, 8)
    assert isclose(pdfimage.yres, 8)
开发者ID:stweil,项目名称:OCRmyPDF,代码行数:33,代码来源:test_pageinfo.py


示例7: set_fp_gpio_voltage

 def set_fp_gpio_voltage(self, value):
     """ Set Front Panel GPIO voltage (in volts)
     3V3 2V5 | Voltage
     -----------------
      0   0  | 1.8 V
      0   1  | 2.5 V
      1   0  | 3.3 V
     Arguments:
         value : 3.3
     """
     assert any([math.isclose(value, nn, abs_tol=0.1) for nn in (3.3,)]),\
         "FP GPIO currently only supports 3.3V"
     if math.isclose(value, 1.8, abs_tol=0.1):
         voltage_reg = 0
     elif math.isclose(value, 2.5, abs_tol=0.1):
         voltage_reg = 1
     elif math.isclose(value, 3.3, abs_tol=0.1):
         voltage_reg = 2
     mask = 0xFFFFFFFF ^ ((0b1 << self.MB_GPIO_CTRL_EN_3V3) | \
                          (0b1 << self.MB_GPIO_CTRL_EN_2V5))
     with self.regs:
         reg_val = self.peek32(self.MB_GPIO_CTRL) & mask
         reg_val = reg_val | (voltage_reg << self.MB_GPIO_CTRL_EN_2V5)
         self.log.trace("Writing MB_GPIO_CTRL to 0x{:08X}".format(reg_val))
         return self.poke32(self.MB_GPIO_CTRL, reg_val)
开发者ID:EttusResearch,项目名称:uhd,代码行数:25,代码来源:e320_periphs.py


示例8: test_query

 def test_query(self):
     l1, u1 = queryweightedmodel(self.q_access_alice_f1, self.ws, self.As,
             self.IC, wf=self.wf)
     l2, u2 = queryweightedmodel(self.q_access_alice_f2, self.ws, self.As,
             self.IC, wf=self.wf)
     l3, u3 = queryweightedmodel(self.q_access_bob_f1, self.ws, self.As,
             self.IC, wf=self.wf)
     l4, u4 = queryweightedmodel(self.q_access_bob_f2, self.ws, self.As,
             self.IC, wf=self.wf)
     l5, u5 = queryweightedmodel(self.q_blacklisted_alice, self.ws, self.As,
             self.IC, wf=self.wf)
     l6, u6 = queryweightedmodel(self.q_blacklisted_bob, self.ws, self.As,
             self.IC, wf=self.wf)
     self.assertTrue(math.isclose(l1, 0.44, abs_tol=1e-2))
     self.assertTrue(math.isclose(u1, 0.44, abs_tol=1e-2))
     self.assertTrue(math.isclose(l2, 0.6, abs_tol=1e-1))
     self.assertTrue(math.isclose(u2, 0.6, abs_tol=1e-1))
     # too much deviation: 0.14 to 0.04
     # self.assertTrue(math.isclose(l3, 0.14, abs_tol=1e-2))
     # self.assertTrue(math.isclose(u3, 0.14, abs_tol=1e-2))
     self.assertTrue(math.isclose(l4, 0.4, abs_tol=1e-1))
     self.assertTrue(math.isclose(u4, 0.4, abs_tol=1e-1))
     self.assertTrue(math.isclose(l5, 0.005, abs_tol=5e-3))
     self.assertTrue(math.isclose(u5, 0.005, abs_tol=5e-3))
     self.assertTrue(math.isclose(l6, 0.017, abs_tol=1e-2))
     self.assertTrue(math.isclose(u6, 0.017, abs_tol=1e-2))
开发者ID:oibot,项目名称:StructuredKB,代码行数:26,代码来源:test_structuredKB.py


示例9: plot_reference_data

def plot_reference_data(ax, atomic_number, ion_stage, estimators_celltimestep, dfpopthision, args, annotatelines):
    nne, Te, TR, W = [estimators_celltimestep[s] for s in ['nne', 'Te', 'TR', 'W']]
    # comparison to Chianti file
    elsym = at.elsymbols[atomic_number]
    elsymlower = elsym.lower()
    if Path('data', f'{elsymlower}_{ion_stage}-levelmap.txt').exists():
        # ax.set_ylim(bottom=2e-3)
        # ax.set_ylim(top=4)
        levelmapfile = Path('data', f'{elsymlower}_{ion_stage}-levelmap.txt').open('r')
        levelnumofconfigterm = {}
        for line in levelmapfile:
            row = line.split()
            levelnumofconfigterm[(row[0], row[1])] = int(row[2]) - 1

        # ax.set_ylim(bottom=5e-4)
        for depfilepath in sorted(Path('data').rglob(f'chianti_{elsym}_{ion_stage}_*.txt')):
            with depfilepath.open('r') as depfile:
                firstline = depfile.readline()
                file_nne = float(firstline[firstline.find('ne = ') + 5:].split(',')[0])
                file_Te = float(firstline[firstline.find('Te = ') + 5:].split(',')[0])
                file_TR = float(firstline[firstline.find('TR = ') + 5:].split(',')[0])
                file_W = float(firstline[firstline.find('W = ') + 5:].split(',')[0])
                # print(depfilepath, file_nne, nne, file_Te, Te, file_TR, TR, file_W, W)
                if (math.isclose(file_nne, nne, rel_tol=0.01) and
                        math.isclose(file_Te, Te, abs_tol=10)):
                    if file_W > 0:
                        continue
                        bbstr = ' with dilute blackbody'
                        color = 'C2'
                        marker = '+'
                    else:
                        bbstr = ''
                        color = 'C1'
                        marker = '^'

                    print(f'Plotting reference data from {depfilepath},')
                    print(f'nne = {file_nne} (ARTIS {nne}) cm^-3, Te = {file_Te} (ARTIS {Te}) K, '
                          f'TR = {file_TR} (ARTIS {TR}) K, W = {file_W} (ARTIS {W})')
                    levelnums = []
                    depcoeffs = []
                    firstdep = -1
                    for line in depfile:
                        row = line.split()
                        try:
                            levelnum = levelnumofconfigterm[(row[1], row[2])]
                            if levelnum in dfpopthision['level'].values:
                                levelnums.append(levelnum)
                                if firstdep < 0:
                                    firstdep = float(row[0])
                                depcoeffs.append(float(row[0]) / firstdep)
                        except (KeyError, IndexError, ValueError):
                            pass
                    ionstr = at.get_ionstring(atomic_number, ion_stage, spectral=False)
                    ax.plot(levelnums, depcoeffs, linewidth=1.5, color=color,
                            label=f'{ionstr} CHIANTI NLTE{bbstr}', linestyle='None', marker=marker, zorder=-1)

        if annotatelines and atomic_number == 28 and ion_stage == 2:
            annotate_emission_line(ax=ax, y=0.04, upperlevel=6, lowerlevel=0, label=r'$\lambda$7378')
            annotate_emission_line(ax=ax, y=0.15, upperlevel=6, lowerlevel=2, label=r'1.939 $\mu$m')
            annotate_emission_line(ax=ax, y=0.26, upperlevel=7, lowerlevel=1, label=r'$\lambda$7412')
开发者ID:lukeshingles,项目名称:artis-tools,代码行数:60,代码来源:nltepops.py


示例10: test_jpg

    def test_jpg(self, directory, file_name, tolerance):
        source_file_path = os.path.join(BASE, 'files', file_name)
        output_file_path = os.path.join(directory, 'test.{}'.format(settings.EXPORT_TYPE))
        format = '{}.{}'.format(settings.EXPORT_MAXIMUM_SIZE, settings.EXPORT_TYPE)
        exporter = ImageExporter(source_file_path=source_file_path, ext='.jpg',
                                 output_file_path=output_file_path, format=format,
                                 metadata={})

        assert not os.path.exists(output_file_path)

        exporter.export()

        assert os.path.exists(output_file_path)

        output_image = Image.open(output_file_path)
        source_image = Image.open(source_file_path)
        source_pixels = list(source_image.getdata())
        output_pixels = list(output_image.getdata())

        assert source_image.size == output_image.size
        assert output_image.mode == 'RGB'
        assert output_image.palette == source_image.palette
        assert output_image.format.lower() == settings.EXPORT_TYPE

        for i in range(100):
            # PIL conversions change some pixels, but first 100 are the same on this one
            assert isclose(source_pixels[i][0], output_pixels[i][0], abs_tol=tolerance)
            assert isclose(source_pixels[i][1], output_pixels[i][1], abs_tol=tolerance)
            assert isclose(source_pixels[i][2], output_pixels[i][2], abs_tol=tolerance)
开发者ID:CenterForOpenScience,项目名称:modular-file-renderer,代码行数:29,代码来源:test_exporter.py


示例11: calc_coverage_threshold

def calc_coverage_threshold(cov_dict):
    '''
    calculate minimum coverage threshold for each key in cov_dict.
    see end of 'alternative parameterization' section of Negative binomial page
    and scipy negative binomial documentation for details of calculation.
    '''
    threshold_dict = {}
    for g in cov_dict:
        mean = float(cov_dict[g]['mean'])
        var = float(cov_dict[g]['variance'])
        q = (var-mean)/var
        n = mean**2/(var-mean)
        p = 1 - q

        ## assert that I did the math correctly.
        assert(isclose(nbinom.mean(n,p), mean))
        assert(isclose(nbinom.var(n,p), var))

        ## find the integer threshold that includes ~95% of REL606 distribution,
        ## excluding 5% on the left hand side.
        my_threshold = nbinom.ppf(0.05,n,p)
        my_threshold_p = nbinom.cdf(my_threshold,n,p)
        threshold_dict[g] = {'threshold':str(my_threshold),
                             'threshold_p':str(my_threshold_p)}
    return threshold_dict
开发者ID:rohanmaddamsetti,项目名称:STLE-analysis,代码行数:25,代码来源:K12-specific-genes.py


示例12: get_hkl_indices_from_streamfile

    def get_hkl_indices_from_streamfile(self, crystal_index, peak_x, peak_y):
        """
        This method returns the hkl indices of the predicted bragg peaks of
        the crystal with the given index at the position (peak_x, peak_y)

        Args:
            crystal_index (int): Index of the crystal from which the unit cell
                is returned.
            peak_x (float): The x coordinate of the peak position
            peak_y (float): The y coordinate of the peak position

        Returns:
            list: The hkl indices
        """

        try:
            crystal = self.crystals[crystal_index]
            self.stream_file.seek(crystal.begin_predicted_peaks_pointer)
            while(self.stream_file.tell() != 
                crystal.end_predicted_peaks_pointer):
                line = self.stream_file.readline()
                matches = re.findall(self._float_matching_regex, line)
               
                if(math.isclose(peak_x, float(matches[7]))
                    and math.isclose(peak_y, float(matches[8]))):
                    return [int(matches[0]), int(matches[1]), int(matches[2])]
        except IOError:
            print("Cannot read the peak information from streamfile: ", 
                self.filename)
        return []
开发者ID:antonbarty,项目名称:cheetah,代码行数:30,代码来源:cfel_streamfile.py


示例13: shear_force

    def shear_force(self, factor=None, figsize=None, verbosity=0, scale=1, offset=(0, 0), show=True, gridplot=False):
        self.plot_structure(figsize, 1, scale=scale, offset=offset, gridplot=gridplot)
        if factor is None:
            max_force = max(map(lambda el: np.max(np.abs(el.shear_force)), self.system.element_map.values()))
            factor = det_scaling_factor(max_force, self.max_val_structure)

        for el in self.system.element_map.values():
            if math.isclose(el.node_1.Ty, 0, rel_tol=1e-5, abs_tol=1e-9) and \
                    math.isclose(el.node_2.Ty, 0, rel_tol=1e-5, abs_tol=1e-9) and el.q_load is None:
                # If True there is no bending moment and no shear, thus no shear force, so no need for plotting.
                continue
            axis_values = plot_values_shear_force(el, factor)
            shear_1 = el.shear_force[0]
            shear_2 = el.shear_force[-1]

            if verbosity == 0:
                node_results = True
            else:
                node_results = False

            self.plot_result(axis_values, shear_1, shear_2, node_results=node_results)
        if show:
            self.plot()
        else:
            return self.fig
开发者ID:ritchie46,项目名称:structural_engineering,代码行数:25,代码来源:mpl.py


示例14: test_dynamic_trapz

def test_dynamic_trapz():
    same_grid = dynamic_trapz(a_curve, 1, 6, 100)
    assert isclose(7.4512822710374, same_grid)
    big_grids = dynamic_trapz(a_curve, 1, 6, 5)
    assert isclose(big_grids, 7.2642983586919)
    small_grids = dynamic_trapz(a_curve, 1, 6, 500)
    assert isclose(small_grids, 7.4533539021642)
开发者ID:robalford,项目名称:IntroPython2015,代码行数:7,代码来源:test_trapz.py


示例15: test_model_load_mem_leak

def test_model_load_mem_leak():
    "testing memory leak on load"
    pytest.xfail("memory leak in learn.load()")

    path = untar_data(URLs.MNIST_TINY)
    data = ImageDataBunch.from_folder(path, ds_tfms=([], []), bs=2)
    learn = cnn_learner(data, models.resnet18, metrics=accuracy)
    this_tests(learn.load)
    gpu_mem_reclaim() # baseline
    used_before = gpu_mem_get_used()

    name = 'mnist-tiny-test-load-mem-leak'
    model_path = learn.save(name, return_path=True)
    _ = learn.load(name)
    if os.path.exists(model_path): os.remove(model_path)
    used_after = gpu_mem_get_used()

    # models.resnet18 loaded in GPU RAM is about 50MB
    # calling learn.load() of a saved and then instantly re-loaded model shouldn't require more GPU RAM
    # XXX: currently w/o running gc.collect() this temporarily leaks memory and causes fragmentation - the fragmentation can't be tested from here, but it'll get automatically fixed once load is fixed. load() must unload first the previous model, gc.collect() and only then load the new one onto cuda.
    assert isclose(used_before, used_after, abs_tol=6), f"load() and used GPU RAM: before load(): {used_before}, after: {used_after}"

    # this shows how it should have been
    gc.collect()
    gpu_cache_clear()
    used_after_reclaimed = gpu_mem_get_used()
    # XXX: not sure where 6MB get lost still but for now it's a small leak - need to test with a bigger model
    assert isclose(used_before, used_after_reclaimed, abs_tol=6),f"load() and used GPU RAM: before load(): {used_before}, after: {used_after}, after gc.collect() {used_after_reclaimed} used"
开发者ID:SiddharthTiwari,项目名称:fastai,代码行数:28,代码来源:test_basic_train.py


示例16: get_alpha_sim

def get_alpha_sim(bug_count, t):

    alpha_min = 1.2
    alpha_max = 4
    alpha = alpha_min
    op_alpha = None
    step = 0.01
    min_diff = 1000000

    while alpha < alpha_max:
        results = []
        for i in range(0, 10):
            bugs, bugs_accu, seq = expected_find_sim(None, t, alpha)
            results.append(len(bugs))
        _diff = bug_count - np.mean(results)
        diff = abs(_diff)
        if diff < min_diff:
            min_diff = diff
            op_alpha = alpha

        alpha += step

    print(op_alpha)
    if math.isclose(op_alpha, alpha_min, rel_tol=1e-6) or math.isclose(op_alpha, alpha_max, rel_tol=1e-6):
        print("WARNING: the range of alpha might not be enough for the fitting.")
    return op_alpha
开发者ID:chubbymaggie,项目名称:fuzzingModel,代码行数:26,代码来源:fuzzying_sim.py


示例17: _determine_normal_force

    def _determine_normal_force(element):
        dx = element.point_1.x - element.point_2.x
        if math.isclose(dx, 0):  # element is vertical
            if element.point_1.z < element.point_2.z:  # point 1 is bottom
                element.N = -element.node_1.Fz  # compression and tension in opposite direction
            else:
                element.N = element.node_1.Fz  # compression and tension in opposite direction

        elif math.isclose(element.alpha, 0):  # element is horizontal
            if element.point_1.x < element.point_2.x:  # point 1 is left
                element.N = -element.node_1.Fx  # compression and tension in good direction
            else:
                element.N = element.node_1.Fx  # compression and tension in opposite direction

        else:
            if math.cos(element.alpha) > 0:
                if element.point_1.x < element.point_2.x:  # point 1 is left
                    if element.node_1.Fx > 0:  # compression in element
                        element.N = -math.sqrt(element.node_1.Fx ** 2 + element.node_1.Fz ** 2)
                    else:
                        element.N = math.sqrt(element.node_1.Fx ** 2 + element.node_1.Fz ** 2)
                else:  # point 1 is right
                    if element.node_1.Fx < 0:  # compression in element
                        element.N = -math.sqrt(element.node_1.Fx ** 2 + element.node_1.Fz ** 2)
                    else:
                        element.N = math.sqrt(element.node_1.Fx ** 2 + element.node_1.Fz ** 2)
开发者ID:damontallen,项目名称:structural_engineering,代码行数:26,代码来源:postprocess.py


示例18: test_ngram_models

def test_ngram_models():
    flatland = DataFile("aima-data/EN-text/flatland.txt").read()
    wordseq = words(flatland)
    P1 = UnigramTextModel(wordseq)
    P2 = NgramTextModel(2, wordseq)
    P3 = NgramTextModel(3, wordseq)

    ## The most frequent entries in each model
    assert P1.top(10) == [(2081, 'the'), (1479, 'of'), (1021, 'and'), (1008, 'to'), (850, 'a'), 
                            (722, 'i'), (640, 'in'), (478, 'that'), (399, 'is'), (348, 'you')]

    assert P2.top(10) == [(368, ('of', 'the')), (152, ('to', 'the')), (152, ('in', 'the')), (86, ('of', 'a')), 
                            (80, ('it', 'is'   )), (71, ('by', 'the' )), (68, ('for', 'the'  )),
                            (68, ('and', 'the' )), (62, ('on', 'the' )), (60, ('to', 'be'))]

    assert P3.top(10) == [(30, ('a', 'straight', 'line')), (19, ('of', 'three', 'dimensions')), 
                            (16, ('the', 'sense', 'of'         )), (13, ('by', 'the', 'sense'   )),
                            (13, ('as', 'well', 'as'           )), (12, ('of', 'the', 'circles' )),
                            (12, ('of', 'sight', 'recognition' )), (11, ('the', 'number', 'of'  )),
                            (11, ('that', 'i', 'had'           )), (11, ('so', 'as', 'to'))]


    assert isclose(P1['the'], 0.0611)

    assert isclose(P2['of', 'the'], 0.0108)

    assert isclose(P3['', '', 'but'], 0.0)
    assert isclose(P3['', '', 'but'], 0.0)
    assert isclose(P3['so', 'as', 'to'], 0.000323)

    assert not P2.cond_prob['went',].dictionary

    assert P3.cond_prob['in','order'].dictionary == {'to': 6}
开发者ID:qzane,项目名称:aima-python,代码行数:33,代码来源:text_test.py


示例19: compare

def compare(to_compare, path, message, processes):
    the_path = (path + '/' + to_compare)
    if platform.system() == 'Windows':  # windows compatibility
        the_path = the_path[the_path.find('/') + 1:]
    with open(to_compare, 'r') as generatedf:
        generated = {}
        for row in csv.DictReader(generatedf):
            try:
                generated[(row['round'], row['name'])] = row
            except KeyError:
                generated[row['round']] = row
    with open(the_path, 'r') as orginialf:
        orginial = {}
        for row in csv.DictReader(orginialf):
            try:
                orginial[(row['round'], row['name'])] = row
            except KeyError:
                orginial[row['round']] = row
    for row in generated:
        for key in generated[row]:
            if key != 'index':
                if generated[row][key] != orginial[row][key]:
                    assert isclose(float(generated[row][key]), float(orginial[row][key])), (
                        to_compare, key, generated[row][key], orginial[row][key])
    for row in orginial:
        for key in orginial[row]:
            if key != 'index':
                if generated[row][key] != orginial[row][key]:
                    assert isclose(float(generated[row][key]), float(orginial[row][key])), (
                        to_compare, key, generated[row][key], orginial[row][key])
开发者ID:DavoudTaghawiNejad,项目名称:abce,代码行数:30,代码来源:start_logging_test.py


示例20: test_servo_values

def test_servo_values():
    p = Device.pin_factory.pin(1)
    with Servo(1) as servo:
        servo.min()
        assert servo.is_active
        assert servo.value == -1
        assert isclose(p.state, 0.05)
        servo.max()
        assert servo.is_active
        assert servo.value == 1
        assert isclose(p.state, 0.1)
        servo.mid()
        assert servo.is_active
        assert servo.value == 0.0
        assert isclose(p.state, 0.075)
        servo.value = 0.5
        assert servo.is_active
        assert servo.value == 0.5
        assert isclose(p.state, 0.0875)
        servo.detach()
        assert not servo.is_active
        assert servo.value is None
        servo.value = 0
        assert servo.value == 0
        servo.value = None
        assert servo.value is None
开发者ID:SteveAmor,项目名称:python-gpiozero,代码行数:26,代码来源:test_outputs.py



注:本文中的math.isclose函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python math.isfinite函数代码示例发布时间:2022-05-27
下一篇:
Python math.hypot函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap