python math.sqrt怎么扩大倍数_Python math.sqrt方法代码示例

本文详细介绍了Python中的math.sqrt方法,包括其用法、参数和返回值。通过29个代码示例展示了如何在不同场景下使用该方法进行平方根计算。这些示例涵盖了从基础的数学运算到深度学习模型的权重初始化等多个方面。
摘要由CSDN通过智能技术生成

本文整理汇总了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;未经允许,请勿转载。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值