精华内容
下载资源
问答
  • Python平方根:math.sqrt()和cmath.sqrt
    2021-03-17 01:46:01

    示例

    该math模块包含-函数,该函数可以计算任何数字的平方根(可以转换为),并且结果始终为:math.sqrt()floatfloat

    import math

    math.sqrt(9)                # 3.0

    math.sqrt(11.11)            # 3.3331666624997918

    math.sqrt(Decimal('6.25'))  # 2.5

    该功能引起了,如果结果将是:math.sqrt()ValueErrorcomplex

    math.sqrt(-10)ValueError:数学域错误

    math.sqrt(x)是快比math.pow(x, 0.5)或x ** 0.5但结果的精确度是一样的。该cmath模块与该模块极为相似math,不同之处在于它可以计算复数,并且所有结果均为a + bi形式。它也可以使用:.sqrt()

    import cmath

    cmath.sqrt(4)  # 2 + 0j

    cmath.sqrt(-4) # 2j

    是什么j?j等于-1的平方根。所有数字都可以采用a + bi或在本例中为+ bj的形式。a是数字中的实数部分,如中的2 2+0j。由于没有虚部,因此b为0。b表示数字中虚部的一部分,如中的2 2j。由于没有任何实质内容,2j因此也可以写成0 + 2j。

    更多相关内容
  • 主要介绍了JavaScript中Math.SQRT2属性的使用详解,是JS入门学习中的基础知识,需要的朋友可以参考下
  • Math.SQRT1_2 例子: <html> <head> <title>JavaScript Math SQRT1_2 Property</title> </head> <body> [removed] var property_value = Math.SQRT1_2 [removed]("Property...
  • 本文整理汇总了Python中math.sqrt方法的典型用法代码示例。如果您正苦于以下问题:Python math.sqrt方法的具体用法?Python math.sqrt怎么用?Python math.sqrt使用的例子?那么恭喜您, 这里精选的方法代码示例或许...

    本文整理汇总了Python中math.sqrt方法的典型用法代码示例。如果您正苦于以下问题:Python math.sqrt方法的具体用法?Python math.sqrt怎么用?Python math.sqrt使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块math的用法示例。

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

    示例1: swirl

    ​点赞 6

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def swirl(x, y, step):

    x -= (u_width / 2)

    y -= (u_height / 2)

    dist = math.sqrt(pow(x, 2) + pow(y, 2)) / 2.0

    angle = (step / 10.0) + (dist * 1.5)

    s = math.sin(angle)

    c = math.cos(angle)

    xs = x * c - y * s

    ys = x * s + y * c

    r = abs(xs + ys)

    r = r * 12.0

    r -= 20

    return (r, r + (s * 130), r + (c * 130))

    # roto-zooming checker board

    开发者ID:pimoroni,项目名称:unicorn-hat-hd,代码行数:18,

    示例2: __init__

    ​点赞 6

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def __init__(self, block, layers, num_classes=1000):

    self.inplanes = 64

    super(MyResNet, self).__init__()

    self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,

    bias=False)

    self.bn1 = nn.BatchNorm2d(64)

    self.relu = nn.ReLU(inplace=True)

    self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)

    # note the increasing dilation

    self.layer1 = self._make_layer(block, 64, layers[0])

    self.layer2 = self._make_layer(block, 128, layers[1], stride=2, dilation=1)

    self.layer3 = self._make_layer(block, 256, layers[2], stride=1, dilation=2)

    self.layer4 = self._make_layer(block, 512, layers[3], stride=1, dilation=4)

    # these layers will not be used

    self.avgpool = nn.AvgPool2d(7)

    self.fc = nn.Linear(512 * block.expansion, num_classes)

    for m in self.modules():

    if isinstance(m, nn.Conv2d):

    n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels

    m.weight.data.normal_(0, math.sqrt(2. / n))

    elif isinstance(m, nn.BatchNorm2d):

    m.weight.data.fill_(1)

    m.bias.data.zero_()

    开发者ID:aleju,项目名称:cat-bbs,代码行数:27,

    示例3: _compute_dE

    ​点赞 6

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def _compute_dE(self, pos=None, lengths=None, weights=None, m=None):

    dEx = 0

    dEy = 0

    d2Ex2 = 0

    d2Ey2 = 0

    d2Exy = 0

    d2Eyx = 0

    for i in pos:

    if i != m:

    xmi = pos[m][0] - pos[i][0]

    ymi = pos[m][1] - pos[i][1]

    xmi2 = xmi * xmi

    ymi2 = ymi * ymi

    xmi_ymi2 = xmi2 + ymi2

    lmi = lengths[m][i]

    kmi = weights[m][i] / (lmi * lmi)

    dEx += kmi * (xmi - (lmi * xmi) / math.sqrt(xmi_ymi2))

    dEy += kmi * (ymi - (lmi * ymi) / math.sqrt(xmi_ymi2))

    d2Ex2 += kmi * (1 - (lmi * ymi2) / math.pow(xmi_ymi2, 1.5))

    d2Ey2 += kmi * (1 - (lmi * xmi2) / math.pow(xmi_ymi2, 1.5))

    res = kmi * (lmi * xmi * ymi) / math.pow(xmi_ymi2, 1.5)

    d2Exy += res

    d2Eyx += res

    return dEx, dEy, d2Ex2, d2Ey2, d2Exy, d2Eyx

    开发者ID:fabriziocosta,项目名称:EDeN,代码行数:26,

    示例4: __init__

    ​点赞 6

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def __init__(self, block, layers, num_classes=1000):

    self.inplanes = 64

    super(ResNet, self).__init__()

    self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,

    bias=False)

    self.bn1 = nn.BatchNorm2d(64)

    self.relu = nn.ReLU(inplace=True)

    # maxpool different from pytorch-resnet, to match tf-faster-rcnn

    self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)

    self.layer1 = self._make_layer(block, 64, layers[0])

    self.layer2 = self._make_layer(block, 128, layers[1], stride=2)

    self.layer3 = self._make_layer(block, 256, layers[2], stride=2)

    # use stride 1 for the last conv4 layer (same as tf-faster-rcnn)

    self.layer4 = self._make_layer(block, 512, layers[3], stride=1)

    for m in self.modules():

    if isinstance(m, nn.Conv2d):

    n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels

    m.weight.data.normal_(0, math.sqrt(2. / n))

    elif isinstance(m, nn.BatchNorm2d):

    m.weight.data.fill_(1)

    m.bias.data.zero_()

    开发者ID:Sunarker,项目名称:Collaborative-Learning-for-Weakly-Supervised-Object-Detection,代码行数:24,

    示例5: _attn

    ​点赞 6

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def _attn(self, q, k, v, sequence_mask):

    w = torch.matmul(q, k)

    if self.scale:

    w = w / math.sqrt(v.size(-1))

    b_subset = self.b[:, :, :w.size(-2), :w.size(-1)]

    if sequence_mask is not None:

    b_subset = b_subset * sequence_mask.view(

    sequence_mask.size(0), 1, -1)

    b_subset = b_subset.permute(1, 0, 2, 3)

    w = w * b_subset + -1e9 * (1 - b_subset)

    w = nn.Softmax(dim=-1)(w)

    w = self.attn_dropout(w)

    return torch.matmul(w, v)

    开发者ID:atcbosselut,项目名称:comet-commonsense,代码行数:18,

    示例6: __call__

    ​点赞 6

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def __call__(self, video):

    for attempt in range(10):

    area = video.shape[-3]*video.shape[-2]

    target_area = random.uniform(0.08, 1.0)*area

    aspect_ratio = random.uniform(3./4, 4./3)

    w = int(round(math.sqrt(target_area*aspect_ratio)))

    h = int(round(math.sqrt(target_area/aspect_ratio)))

    if random.random() < 0.5:

    w, h = h, w

    if w <= video.shape[-2] and h <= video.shape[-3]:

    x1 = random.randint(0, video.shape[-2]-w)

    y1 = random.randint(0, video.shape[-3]-h)

    video = video[..., y1:y1+h, x1:x1+w, :]

    return resize(video, (self.size, self.size), self.interpolation)

    # Fallback

    scale = Scale(self.size, interpolation=self.interpolation)

    crop = CenterCrop(self.size)

    return crop(scale(video))

    开发者ID:jthsieh,项目名称:DDPAE-video-prediction,代码行数:26,

    示例7: genCubeVector

    ​点赞 6

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def genCubeVector(x, y, z, x_mult=1, y_mult=1, z_mult=1):

    """Generates a map of vector lengths from the center point to each coordinate

    x - width of matrix to generate

    y - height of matrix to generate

    z - depth of matrix to generate

    x_mult - value to scale x-axis by

    y_mult - value to scale y-axis by

    z_mult - value to scale z-axis by

    """

    cX = (x - 1) / 2.0

    cY = (y - 1) / 2.0

    cZ = (z - 1) / 2.0

    def vect(_x, _y, _z):

    return int(math.sqrt(math.pow(_x - cX, 2 * x_mult) +

    math.pow(_y - cY, 2 * y_mult) +

    math.pow(_z - cZ, 2 * z_mult)))

    return [[[vect(_x, _y, _z) for _z in range(z)] for _y in range(y)] for _x in range(x)]

    开发者ID:ManiacalLabs,项目名称:BiblioPixelAnimations,代码行数:22,

    示例8: distance

    ​点赞 6

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def distance(origin, destination):

    """Determine distance between 2 sets of [lat,lon] in km"""

    lat1, lon1 = origin

    lat2, lon2 = destination

    radius = 6371 # km

    dlat = math.radians(lat2 - lat1)

    dlon = math.radians(lon2 - lon1)

    a = (math.sin(dlat / 2) * math.sin(dlat / 2) +

    math.cos(math.radians(lat1)) *

    math.cos(math.radians(lat2)) * math.sin(dlon / 2) *

    math.sin(dlon / 2))

    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))

    d = radius * c

    return d

    开发者ID:NatanaelAntonioli,项目名称:L.E.S.M.A,代码行数:19,

    示例9: __init__

    ​点赞 6

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def __init__(self, block, layers, in_channels=3):

    self.inplanes = 64

    super(ResNet, self).__init__()

    self.conv1 = nn.Conv2d(in_channels, 64, kernel_size=7, stride=2, padding=3,

    bias=False)

    self.bn1 = nn.BatchNorm2d(64)

    self.relu = nn.ReLU(inplace=True)

    self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)

    self.layer1 = self._make_layer(block, 64, layers[0])

    self.layer2 = self._make_layer(block, 128, layers[1], stride=2)

    self.layer3 = self._make_layer(block, 256, layers[2], stride=2)

    self.layer4 = self._make_layer(block, 512, layers[3], stride=2)

    for m in self.modules():

    if isinstance(m, nn.Conv2d):

    n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels

    m.weight.data.normal_(0, math.sqrt(2. / n))

    elif isinstance(m, nn.BatchNorm2d):

    m.weight.data.fill_(1)

    m.bias.data.zero_()

    开发者ID:toodef,项目名称:neural-pipeline,代码行数:22,

    示例10: __init__

    ​点赞 6

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def __init__(self, interval, stat_func=None, pattern='.*', sort=False):

    if stat_func is None:

    def asum_stat(x):

    """returns |x|/size(x), async execution."""

    return ndarray.norm(x)/sqrt(x.size)

    stat_func = asum_stat

    self.stat_func = stat_func

    self.interval = interval

    self.activated = False

    self.queue = []

    self.step = 0

    self.exes = []

    self.re_prog = re.compile(pattern)

    self.sort = sort

    def stat_helper(name, array):

    """wrapper for executor callback"""

    array = ctypes.cast(array, NDArrayHandle)

    array = NDArray(array, writable=False)

    if not self.activated or not self.re_prog.match(py_str(name)):

    return

    self.queue.append((self.step, py_str(name), self.stat_func(array)))

    self.stat_helper = stat_helper

    开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:24,

    示例11: matthewscc

    ​点赞 6

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def matthewscc(self):

    """

    Calculate the Matthew's Correlation Coefficent

    """

    if not self.total_examples:

    return 0.

    true_pos = float(self.true_positives)

    false_pos = float(self.false_positives)

    false_neg = float(self.false_negatives)

    true_neg = float(self.true_negatives)

    terms = [(true_pos + false_pos),

    (true_pos + false_neg),

    (true_neg + false_pos),

    (true_neg + false_neg)]

    denom = 1.

    for t in filter(lambda t: t != 0., terms):

    denom *= t

    return ((true_pos * true_neg) - (false_pos * false_neg)) / math.sqrt(denom)

    开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:21,

    示例12: set_verbosity

    ​点赞 6

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def set_verbosity(self, verbose=False, print_func=None):

    """Switch on/off verbose mode

    Parameters

    ----------

    verbose : bool

    switch on/off verbose mode

    print_func : function

    A function that computes statistics of initialized arrays.

    Takes an `NDArray` and returns an `str`. Defaults to mean

    absolute value str((|x|/size(x)).asscalar()).

    """

    self._verbose = verbose

    if print_func is None:

    def asum_stat(x):

    """returns |x|/size(x), async execution."""

    return str((ndarray.norm(x)/sqrt(x.size)).asscalar())

    print_func = asum_stat

    self._print_func = print_func

    return self

    开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:22,

    示例13: _init_weight

    ​点赞 6

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def _init_weight(self, name, arr):

    shape = arr.shape

    hw_scale = 1.

    if len(shape) < 2:

    raise ValueError('Xavier initializer cannot be applied to vector {0}. It requires at'

    ' least 2D.'.format(name))

    if len(shape) > 2:

    hw_scale = np.prod(shape[2:])

    fan_in, fan_out = shape[1] * hw_scale, shape[0] * hw_scale

    factor = 1.

    if self.factor_type == "avg":

    factor = (fan_in + fan_out) / 2.0

    elif self.factor_type == "in":

    factor = fan_in

    elif self.factor_type == "out":

    factor = fan_out

    else:

    raise ValueError("Incorrect factor type")

    scale = np.sqrt(self.magnitude / factor)

    if self.rnd_type == "uniform":

    random.uniform(-scale, scale, out=arr)

    elif self.rnd_type == "gaussian":

    random.normal(0, scale, out=arr)

    else:

    raise ValueError("Unknown random type")

    开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:27,

    示例14: _get_lbmult

    ​点赞 6

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def _get_lbmult(self, nup):

    """Returns lr scaling factor for large batch according to warmup schedule

    (to be implemented)

    """

    nwup = self.warmup_epochs * self.updates_per_epoch

    strategy = self.warmup_strategy

    maxmult = float(self.batch_scale)

    if nup >= nwup:

    mult = maxmult

    elif nwup <= 1:

    mult = 1.0

    else:

    if (strategy == 'linear'):

    mult = 1.0 + (maxmult - 1) * nup / nwup

    elif (strategy == 'power2'):

    mult = 1.0 + (maxmult-1) * (nup*nup)/(nwup*nwup)

    elif (strategy == 'sqrt'):

    mult = 1.0 + (maxmult - 1) * math.sqrt(float(nup) / nwup)

    else:

    mult = 1.0

    return mult

    开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:23,

    示例15: update

    ​点赞 6

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def update(self, index, weight, grad, state):

    assert(isinstance(weight, NDArray))

    assert(isinstance(grad, NDArray))

    self._update_count(index)

    lr = self._get_lr(index)

    wd = self._get_wd(index)

    is_sparse = grad.stype == 'row_sparse'

    history = state

    if is_sparse:

    kwargs = {'epsilon': self.float_stable_eps,

    'rescale_grad': self.rescale_grad}

    if self.clip_gradient:

    kwargs['clip_gradient'] = self.clip_gradient

    sparse.adagrad_update(weight, grad, history, out=weight, lr=lr, wd=wd, **kwargs)

    else:

    grad = grad * self.rescale_grad

    if self.clip_gradient is not None:

    grad = clip(grad, -self.clip_gradient, self.clip_gradient)

    history[:] += square(grad)

    div = grad / sqrt(history + self.float_stable_eps)

    weight[:] += (div + weight * wd) * -lr

    开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:25,

    示例16: update

    ​点赞 6

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def update(self, index, weight, grad, state):

    self._update_count(index)

    wd = self._get_wd(index)

    lr = self._get_lr(index)

    num_rows = weight.shape[0]

    dn, n = state

    for row in range(num_rows):

    all_zeros = mx.test_utils.almost_equal(grad[row].asnumpy(), np.zeros_like(grad[row].asnumpy()))

    if all_zeros and self.lazy_update:

    continue

    grad[row] = grad[row] * self.rescale_grad

    if self.clip_gradient is not None:

    mx.nd.clip(grad[row], -self.clip_gradient, self.clip_gradient, out=grad[row])

    #update dn, n

    dn[row] += grad[row] - (mx.nd.sqrt(n[row] + grad[row] * grad[row]) - mx.nd.sqrt(n[row])) * weight[row] / lr

    n[row] += grad[row] * grad[row]

    # update weight

    weight[row] = (mx.nd.sign(dn[row]) * self.lamda1 - dn[row]) / \

    ((self.beta + mx.nd.sqrt(n[row])) / lr + wd) * (mx.nd.abs(dn[row]) > self.lamda1)

    开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:24,

    示例17: get_privacy_spent

    ​点赞 6

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def get_privacy_spent(self, sess, target_eps=None):

    """Report the spending so far.

    Args:

    sess: the session to run the tensor.

    target_eps: the target epsilon. Unused.

    Returns:

    the list containing a single EpsDelta, with values as Python floats (as

    opposed to numpy.float64). This is to be consistent with

    MomentAccountant which can return a list of (eps, delta) pair.

    """

    # pylint: disable=unused-argument

    unused_target_eps = target_eps

    eps_squared_sum, delta_sum = sess.run([self._eps_squared_sum,

    self._delta_sum])

    return [EpsDelta(math.sqrt(eps_squared_sum), float(delta_sum))]

    开发者ID:ringringyi,项目名称:DOTA_models,代码行数:19,

    示例18: tunnel

    ​点赞 5

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def tunnel(x, y, step):

    speed = step / 100.0

    x -= (u_width / 2)

    y -= (u_height / 2)

    xo = math.sin(step / 27.0) * 2

    yo = math.cos(step / 18.0) * 2

    x += xo

    y += yo

    if y == 0:

    if x < 0:

    angle = -(math.pi / 2)

    else:

    angle = (math.pi / 2)

    else:

    angle = math.atan(x / y)

    if y > 0:

    angle += math.pi

    angle /= 2 * math.pi # convert angle to 0...1 range

    hyp = math.sqrt(math.pow(x, 2) + math.pow(y, 2))

    shade = hyp / 2.1

    shade = 1 if shade > 1 else shade

    angle += speed

    depth = speed + (hyp / 10)

    col1 = hue_to_rgb[step % 255]

    col1 = (col1[0] * 0.8, col1[1] * 0.8, col1[2] * 0.8)

    col2 = hue_to_rgb[step % 255]

    col2 = (col2[0] * 0.3, col2[1] * 0.3, col2[2] * 0.3)

    col = col1 if int(abs(angle * 6.0)) % 2 == 0 else col2

    td = .3 if int(abs(depth * 3.0)) % 2 == 0 else 0

    col = (col[0] + td, col[1] + td, col[2] + td)

    col = (col[0] * shade, col[1] * shade, col[2] * shade)

    return (col[0] * 255, col[1] * 255, col[2] * 255)

    开发者ID:pimoroni,项目名称:unicorn-hat-hd,代码行数:34,

    示例19: gelu

    ​点赞 5

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def gelu(input_tensor):

    """Gaussian Error Linear Unit.

    This is a smoother version of the RELU.

    Original paper: https://arxiv.org/abs/1606.08415

    Args:

    input_tensor: float Tensor to perform activation.

    Returns:

    `input_tensor` with the GELU activation applied.

    """

    cdf = 0.5 * (1.0 + tf.erf(input_tensor / tf.sqrt(2.0)))

    return input_tensor * cdf

    开发者ID:Socialbird-AILab,项目名称:BERT-Classification-Tutorial,代码行数:16,

    示例20: distance

    ​点赞 5

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def distance(a1, a2):

    """

    We're going to return the distance between two objects. That calculation

    is easy if they are both located in space, but what if one of them is

    not? For now, we will return 0, but is that right?

    """

    if (not a1.is_located()) or (not a2.is_located()):

    return 0.0

    else:

    return sqrt(

    ((a2.get_x() - a1.get_x()) ** 2)

    + ((a2.get_y() - a1.get_y()) ** 2)

    )

    开发者ID:gcallah,项目名称:indras_net,代码行数:15,

    示例21: get_max_distance

    ​点赞 5

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def get_max_distance(self):

    return sqrt((self.height ** 2) + (self.width ** 2))

    开发者ID:gcallah,项目名称:indras_net,代码行数:4,

    示例22: calc_heat

    ​点赞 5

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def calc_heat(self, group, coord):

    heat_strength = 0

    for heat in group:

    distance = sqrt(

    ((coord[X] - group[heat].get_x()) ** 2)

    + ((coord[Y] - group[heat].get_y()) ** 2)

    )

    if distance != 0:

    heat_strength += 1 / ((distance) ** 2)

    else:

    heat_strength += sys.maxsize

    heat_strength *= -1

    return heat_strength

    开发者ID:gcallah,项目名称:indras_net,代码行数:15,

    示例23: get_max_dist

    ​点赞 5

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def get_max_dist(self):

    """

    Args: none

    Returns: The furthest move possible in this env.

    """

    return math.sqrt(self.width**2 + self.height**2)

    开发者ID:gcallah,项目名称:indras_net,代码行数:9,

    示例24: dist

    ​点赞 5

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def dist(self, agent1, agent2):

    """

    Arguments:

    Two grid agents.

    Returns:

    The Euclidian distance between the two

    agents. There isn't numerical ill-conditioning

    with this because the positions are integers. If

    there are any applications where positions are given

    by nonintegral values, use caution.

    """

    return math.sqrt((agent1.pos[X]-agent2.pos[X])**2

    + (agent1.pos[Y]-agent2.pos[Y])**2)

    开发者ID:gcallah,项目名称:indras_net,代码行数:16,

    示例25: dir_info

    ​点赞 5

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def dir_info(self, agent):

    directions = {N: 0, S: 0, E: 0, W: 0}

    total = 0

    creatures = agent.neighbor_iter(sq_v=10)

    for creature in creatures:

    if type(creature) == agent.other:

    othr = creature.pos

    xa = agent.pos[X]

    ya = agent.pos[Y]

    # North constitutes upper quadrant and positive diagonal line

    if(-othr[X]+(ya+xa) < othr[Y] and othr[Y] >= othr[X] + (ya-xa)):

    dist = math.sqrt((ya-othr[Y])**2 + (xa-othr[X])**2)

    directions[N] += 1/dist

    total += 1/dist

    # South constitutes lower quadrant and negative diagonal line

    elif(othr[X]+(ya-xa) >= othr[Y] and othr[Y] < -othr[X]+(ya+xa)):

    dist = math.sqrt((ya-othr[Y])**2 + (xa-othr[X])**2)

    directions[S] += 1/dist

    total += 1/dist

    # East constitutes left quadrant and negative diagonal line

    elif(othr[Y]-(ya-xa) > othr[X] and othr[X] <= -othr[Y]+(ya+xa)):

    dist = math.sqrt((ya-othr[Y])**2 + (xa-othr[X])**2)

    directions[E] += 1/dist

    total += 1/dist

    # West constitutes right quadrant and positive diagonal line

    else:

    dist = math.sqrt((ya-othr[Y])**2 + (xa-othr[X])**2)

    directions[W] += 1/dist

    total += 1/dist

    return directions, total

    # figures out where all the humans are and moves zombies towards them

    开发者ID:gcallah,项目名称:indras_net,代码行数:35,

    示例26: __init__

    ​点赞 5

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def __init__(self, coords, T=-1, alpha=-1, stopping_T=-1, stopping_iter=-1):

    self.coords = coords

    self.N = len(coords)

    self.T = math.sqrt(self.N) if T == -1 else T

    self.T_save = self.T # save inital T to reset if batch annealing is used

    self.alpha = 0.995 if alpha == -1 else alpha

    self.stopping_temperature = 1e-8 if stopping_T == -1 else stopping_T

    self.stopping_iter = 100000 if stopping_iter == -1 else stopping_iter

    self.iteration = 1

    self.nodes = [i for i in range(self.N)]

    self.best_solution = None

    self.best_fitness = float("Inf")

    self.fitness_list = []

    开发者ID:chncyhn,项目名称:simulated-annealing-tsp,代码行数:17,

    示例27: dist

    ​点赞 5

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def dist(self, node_0, node_1):

    """

    Euclidean distance between two nodes.

    """

    coord_0, coord_1 = self.coords[node_0], self.coords[node_1]

    return math.sqrt((coord_0[0] - coord_1[0]) ** 2 + (coord_0[1] - coord_1[1]) ** 2)

    开发者ID:chncyhn,项目名称:simulated-annealing-tsp,代码行数:8,

    示例28: __init__

    ​点赞 5

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def __init__(self, titles, increasing, save_to_fp):

    assert len(titles) == len(increasing)

    n_plots = len(titles)

    self.titles = titles

    self.increasing = dict([(title, incr) for title, incr in zip(titles, increasing)])

    self.colors = ["red", "blue", "cyan", "magenta", "orange", "black"]

    self.nb_points_max = 500

    self.save_to_fp = save_to_fp

    self.start_batch_idx = 0

    self.autolimit_y = False

    self.autolimit_y_multiplier = 5

    #self.fig, self.axes = plt.subplots(nrows=2, ncols=2, figsize=(20, 20))

    nrows = max(1, int(math.sqrt(n_plots)))

    ncols = int(math.ceil(n_plots / nrows))

    width = ncols * 10

    height = nrows * 10

    self.fig, self.axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(width, height))

    if nrows == 1 and ncols == 1:

    self.axes = [self.axes]

    else:

    self.axes = self.axes.flat

    title_to_ax = dict()

    for idx, (title, ax) in enumerate(zip(self.titles, self.axes)):

    title_to_ax[title] = ax

    self.title_to_ax = title_to_ax

    self.fig.tight_layout()

    self.fig.subplots_adjust(left=0.05)

    开发者ID:aleju,项目名称:cat-bbs,代码行数:35,

    示例29: _compute_dm

    ​点赞 5

    # 需要导入模块: import math [as 别名]

    # 或者: from math import sqrt [as 别名]

    def _compute_dm(self, pos=None, lengths=None, weights=None, m=None):

    dEx = 0

    dEy = 0

    for i in pos:

    if i != m:

    xmi = pos[m][0] - pos[i][0]

    ymi = pos[m][1] - pos[i][1]

    xmi2 = xmi * xmi

    ymi2 = ymi * ymi

    xmi_ymi2 = xmi2 + ymi2

    lmi = lengths[m][i]

    kmi = weights[m][i] / (lmi * lmi)

    dEx += kmi * (xmi - (lmi * xmi) / math.sqrt(xmi_ymi2))

    dEy += kmi * (ymi - (lmi * ymi) / math.sqrt(xmi_ymi2))

    return math.sqrt(dEx * dEx + dEy * dEy)

    开发者ID:fabriziocosta,项目名称:EDeN,代码行数:17,

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

    展开全文
  • Java Math.sqrt()方法

    2021-04-23 10:57:39
    描述java.lang.Math.sqrt(double a)返回正确舍入的一个double值的正平方根。特殊情况:如果参数是NaN或小于为零,那么结果是NaN.如果参数是正无穷大,那么结果为正无穷大.如果参数是正零或负零,那么结果是一样的...

    描述

    java.lang.Math.sqrt(double a) 返回正确舍入的一个double值的正平方根。特殊情况:

    如果参数是NaN或小于为零,那么结果是NaN.

    如果参数是正无穷大,那么结果为正无穷大.

    如果参数是正零或负零,那么结果是一样的参数.

    否则,其结果是最接近真正的数学平方根的参数值的double值。

    声明

    以下是java.lang.Math.sqrt()方法的声明

    public static double sqrt(double a)

    参数

    a -- a value.

    返回值

    此方法返回一个正平方根。如果参数是NaN或小于为零,那么结果为NaN。

    异常

    NA

    实例

    下面的例子说明了如何使用lang.Math.sqrt()方法。

    package com.yiibai;

    import java.lang.*;

    public class MathDemo {

    public static void main(String[] args) {

    // get two double numbers numbers

    double x = 9;

    double y = 25;

    // print the square root of these doubles

    System.out.println("Math.sqrt(" + x + ")=" + Math.sqrt(x));

    System.out.println("Math.sqrt(" + y + ")=" + Math.sqrt(y));

    }

    }

    让我们来编译和运行上面的程序,这将产生以下结果:

    Math.sqrt(9)=3.0

    Math.sqrt(25)=5.0

    【转载】C&num;使用Math&period;Sqrt方法进行开平方操作

    在C#的数学数值运算中,有时候需要进行对数值进行开平方操作,C#的数值计算类Math类中内置了开平方操作的方法Sqrt,直接调用此方法可计算出相应的平方值,Math.Sqrt方法签名为:double ...

    为什么要用Math&period;sqrt&lpar;i&rpar;方法

    java 练习题 判断 101-200 之间有多少个素数,并输出所有素数 public class Prime { public static int count = 0; public static ...

    java代码Math&period;sqrt

    总结:这个判断小数的题目,当时全只2有一个人想出了结果.老师很开心.我很桑心~~~~ 我没想到要取膜,我只想到了除以等于0就够了.至于中间的“取膜”,我没凑齐来,还是不够灵活 package com. ...

    无线网络覆盖-java中,用Math&period;sqrt&lpar;&rpar;时,必须要注意小数问题

    时间限制:3000 ms  |  内存限制:65535 KB 难度:3 描述 我们的乐乐同学对于网络可算得上是情有独钟,他有一个计划,那就是用无线网覆盖郑州大学. 现在学校给了他一个机会,因此他要购买 ...

    解决java&period;math&period;BigDecimal divide方法运算结果为无限小数问题

    http://samueli.iteye.com/blog/224755 BigDecimal除法运算报错,错误如下:Non-terminating decimal expansion; no exa ...

    【java】Java&period;math&period;BigDecimal&period;subtract&lpar;&rpar;方法实例

    java.math.BigDecimal.subtract(BigDecimal subtrahend) 返回一个BigDecimal,其值为 (this - subtrahend), 精度为 max ...

    Java&period;math&period;BigDecimal&period;abs&lpar;&rpar;方法

    java.math.BigDecimal.abs()返回一个BigDecimal,其值是此BigDecimal的绝对值,其标度是this.scale(). 声明 以下是java.math.BigDec ...

    java&period;math&period;&ast;&semi;&lpar;一&rpar;

    package com.test; /* Math类: java.lang.Math类中包含基本的数字操作,如指数.对数.平方根和三角函数. java.math是一个包,提供用于执行任意精度整数(Bi ...

    14-02 Java Math类,Random类,System类,BigDecimal类

    Math类 Math的方法 package cn.itcast_01; /* * Math:用于数学运算的类. * 成员变量: * public static final double PI * pu ...

    随机推荐

    H5页面左图右边文字如何布局

    html>

        

    在使用SQLite插入数据时出现乱码的解决办法

    在VC++中通过sqlite3.dll接口对sqlite数据库进行操作,包括打开数据库,插入,查询数据库等,如果操作接口输入参数包含中文字符,会导致操作异常.例如调用sqlite3_open打开数 ...

    latex公式中的空格如何表示

    两个quad空格 a \qquad b 两个m的宽度 quad空格 a \quad b 一个m的宽度 大空格 a\ b 1/3m宽度 中等空格 a\;b 2/7m宽度 小空格 a\,b 1/6m宽度 ...

    Linux远程登录

    Linux远程登录 远程登录 关闭linux的防火墙 /etc/init.d/iptables stop 启动VNC服务器 Vncserver & 然后记住desktop is localho ...

    同步fifo的verilogHDL设计实例

    原创 设计一个fifo,输入16bit,输出16bit的data,寻址宽度5bit,有空满标志. top 层如下所示: /* date : 2014/10/14 version : modelsim ...

    从零开始学 Web 之 Ajax(七)跨域

    大家好,这里是「 从零开始学 Web 系列教程 」,并在下列地址同步更新...... github:https://github.com/Daotin/Web 微信公众号:Web前端之巅 博客园:ht ...

    msp430学习笔记-ADC12

    本文引用:http://bbs.ednchina.com/BLOG_ARTICLE_3013748.HTM MSP430单片机的ADC12模块是一个12位精度的A/D转换模块,它具有高速度,通用性等特 ...

    基于CRF的中文分词

    http://biancheng.dnbcw.info/java/341268.html CRF简介 Conditional Random Field:条件随机场,一种机器学习技术(模型) CRF由J ...

    &lbrack;转&rsqb; JSON转换

    转载自:http://www.360doc.com/content/12/0413/14/9529755_203286509.shtml# JSON简介 JSON(JavaScript Object ...

    弹出层小插件之&lpar;一&rpar;sweetalert

    //弹出层小插件之(一)sweetalert 1.引入sweetalert.css 2.引入sweetalert.min.js 下载地址:http://t4t5.github.io/sweetaler ...

    展开全文
  • 全屏java.lang.Math.sqrt(double a)返回double值的舍入的正平方根正值。特殊情况:如果参数为NaN或小于零,那么结果为NaN。如果参数为正无穷大,那么结果为正无穷大。如果参数为正零或负零,那么结果同参数一样。...

    全屏

    java.lang.Math.sqrt(double a)返回double值的舍入的正平方根正值。特殊情况:如果参数为NaN或小于零,那么结果为NaN。

    如果参数为正无穷大,那么结果为正无穷大。

    如果参数为正零或负零,那么结果同参数一样。

    否则,结果是最接近参数值的真实数学平方根的double值。

    声明

    以下是java.lang.Math.sqrt()方法的声明public static double sqrt(double a)

    参数a -- 一个值

    返回值

    此方法返回正平方根。如果参数为NaN或小于零,则结果为NaN。

    异常NA

    例子

    下面的例子显示lang.Math.sqrt()方法的使用。package cn.sxt;

    import java.lang.*;

    public class MathDemo {

    public static void main(String[] args) {

    // get two double numbers numbers

    double x = 9;

    double y = 25;

    // print the square root of these doubles

    System.out.println("Math.sqrt(" + x + ")=" + Math.sqrt(x));

    System.out.println("Math.sqrt(" + y + ")=" + Math.sqrt(y));

    }

    }

    让我们来编译和运行上面的程序,这将产生以下结果:Math.sqrt(9)=3.0

    Math.sqrt(25)=5.0

    分享到:

    0评论

    14487a65ea137d8f9ac97cdce44a0324.png

    展开全文
  • } } 发现 第二for循环不用 Math.sqrt(i) 总是有问题 然后,发现了这个问题:为什么要用Math.sqrt(i)方法(返回正确舍入的 double 值的正平方根)? 因为,只需要判断到这个值, 例如:判断100,只需要判断到10就...
  • 加油Math.round()Math.pow()Math.sqrt() Math.round() math.round(x)的作用通俗讲就是对x进行"四舍五入",对0.5要进行判断对待。 math.round()的原理是对传入的参数+0.5之后,再向下取整得到的数就是返回的结果。这里...
  • js实现Math.sqrt

    2020-12-25 16:18:31
    // 二分法求平方根 const mySqrt = (n) => { if (isNaN(n)) return NaN; if (n === 0 || n === 1) return n; var low = 0, high = n, pivot = (low + high) / 2, ... if (Math.pow(pivot, 2)...
  • math.sqrt 有问题 JavaScript | Math.sqrt()方法 (JavaScript | Math.sqrt() Method) The Math.sqrt() method is inbuilt in JavaScript to find the square root of a number. In this tutorial, we will learn ...
  • ## 我们请来他们全家(感觉想骂人),这时候我们称呼math的家人(方法,如sqrt)的时候, 就会说:“math 家的sqrt” ## 对应代码如下: import math print math.sqrt(4) 2.0 ## (2) 从模块中单独引入该方法...
  • math.sqrt 有问题 Python math.sqrt()方法 (Python math.sqrt() method) math.sqrt() method is a library method of math module, it is used to find the square root of a given number, it accepts a positive ...
  • 为了在Java中获得数字的平方根,我们使用java.lang.Math.pow()方法。...声明-java.lang.Math.sqrt()方法的声明如下-publicstaticdoublesqrt(doublea)其中a是要找到其平方根的数字。让我们看一个程序,在其中使用Math...
  • math.sqrt 有问题 JavaScript | Math.SQRT2属性 (JavaScript | Math.SQRT2 Property) Math.SQRT2 is a property in math library of JavaScript that is used to find the value of square root of 2. It is ...
  • JavaScript用Math.sqrt()求平方根

    千次阅读 2020-12-20 01:57:23
    1. 基本概念Math.sqrt()方法的名字sqrt是"square root"的缩写,它代表的正是平方根。因此,Math.sqrt()方法的作用就是用来求一个数的平方根。它的语法结构如下所示:Math.sqrt(x);参数x应该是一个数字,即它的类型...
  • java.lang.Math.sqrt(double a) 返回一个数字a的正平方根,返回结果是double型 java.lang.Math.pow(double a, double b) 返回一个数字a的b次方,返回结果是double型 有意思的是, 我们也可以通过Math.pow()实现开方...
  • 这到底是为何,sqrt调用了python中另外的内置函数??
  • 表示点的坐标并且用math.hypot来表示两点间的距离 import sheffield.*; public class w { public static void main(String[] args) { EasyReader keyboard = new EasyReader(); double a = keyboard.readDouble...
  • 深入学习java源码之Math.sin()与 Math.sqrt() native关键字 凡是一种语言,都希望是纯。比如解决某一个方案都喜欢就单单这个语言来写即可。Java平台有个用户和本地C代码进行互操作的API,称为JNI native...
  • js实现Math.sqrt()方法

    千次阅读 2020-06-04 11:06:10
    之前面试的时候,面试有一道题,要记算10的平方根,并且精确到0.01,我也是想了一会才想到了一种简单粗暴的方法,也算是完成了;... Number.EPSILON:javascript计算的最小误差值,相当于Math.pow(2,-52)Math.pow(2,-52)
  • /// <summary> /// 开平方根(牛顿迭代法) /// </summary> /// <param name="c">...public static decimal Sqrt(decimal c) { if (c < 0) { return decimal.MinValue; } decimal e = 1e-
  • Java 中 Math.sqrt()方法

    千次阅读 2019-09-05 09:47:27
    Java Math.sqrt()方法 描述 java.lang.Math.sqrt(double a)返回正确舍入的一个double值的正平方根。特殊情况: 如果参数是NaN或小于为零,那么结果是NaN. 如果参数是正无穷大,那么结果为正无穷大. ...
  • math.sqrt JavaScript | Math.SQRT1_2属性 (JavaScript | Math.SQRT1_2 Property) Math.SQRT1_2 is a property in math library of JavaScript that is used to find the value of square root of ½. It is ...
  • Math.pow() 能实现 Math.cbrt() 和 Math.sqrt() 的功能,但并不完全相同。 1. Math.pow()和Math.cbrt()的区别 function isCube(m, n){ return Math.cbrt(m)===n; } console.log(isCube(27,3)) //output: ...
  • math.sqrt()函数 Python函数内部的求平方根的方法。直接调用就可以。 牛顿迭代法求平方根 公式: 以上公式接受一个值n,并且通过再每一次迭代中将newguess赋值给oldguess来反复猜测平方根。大概反复迭代20次左右...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 208,241
精华内容 83,296
关键字:

math.sqrt

友情链接: tuezvd.rar