Runtimewarning invalid value encountered in sqrt python

Ай, Карамба, у меня RuntimeWarning: invalid value encountered in sqrt

Привет всем,очень нужна помощь в устранении ошибки.
Вроде все логично,программа строит нужные графики,считает все параметры абсолютно верно,но в какой-то момент выдает ошибку в вычислении функции( значения положительной половины окружности в координатах),причем зависимость я так и не смог найти. Входные данные сугубо положительные,типа float .
Буду благодарен за помощь,ибо сам не справляюсь(
Есть подозрения,что беда в np.linspace,который является аргументом Mrc ,что приводит к RuntimeWarning: invalid value encountered in sqrt
y =np.sqrt(r * r — (x — x0) * (x — x0)),
тип данных мб не тот,но float и комплекс не решают эту проблему

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
def Mrc(x, r, x0): y =np.sqrt(r * r - (x - x0) * (x - x0)) return y Dlunk = float(input()) Dotv = float(input()) a = float(input()) b = float(input()) Pkgs = float(input()) S=a*b*N/100 F=np.pi* Dlunk * Dotv/100 Sit = float(Pkgs / (10*S)) Pv = Pkgs / (10*F) Ki = Pv/Sit TanFi0 =0.5*(Pv-Sit)/np.sqrt(Sit*Pv) Fi0=np.arctan(TanFi0)*180/np.pi C0i = np.sqrt(Sit * Pv) TanFi=(np.sqrt(Pv)-np.sqrt(Sit))*0.5/(np.sqrt(np.sqrt(Pv*Sit))) Fi = np.arctan(TanFi) * 180 / np.pi Ci=np.sqrt(np.sqrt(Pv*Sit))*(np.sqrt(Pv)+np.sqrt(Sit))*0.5 Sis=Pv+np.sqrt(Sit*Pv) Sivs=2*Pkgs / (10*(S+F)) Khr=Sis/Sivs KPuass=1.4/(Khr-2.05) Si3s=2*Pkgs Xc1 = (-1) * Sit R1 = Sit Xc2 = 0 R2 = Sit * Pv * 2/ (Sit + Pv) Xc3 = (Pv - Sit) /2 R3 = (Pv - Sit) /2 Xc4 = (Pv + C0i) / 2 R4 = (Pv + C0i) / 2 Xc5=(Pv+2*C0i+Sit)/2 R5=(Pv+2*C0i-Sit)/2 Xc6=Pv+C0i R6=Pv Xc7=(Pv+C0i)*(2+np.sqrt(Pv/Sit))/2 R7=(Pv+C0i)*np.sqrt(Pv/Sit)/2 Xc8=(Pv+C0i)*(Pv/Sit+np.sqrt(Pv/Sit)-2)/4 R8=3*C0i/2+((Pv-3*Sit)*Pv/Sit)/4 Xc9 = (Pv + Sit) / 2 R9 = Sit + Pv / 2 X_l1 = np.linspace(Xc1-R1,Xc1+R1, 1000)#графика кругов 1-8 Y1 = Mrc(X_l1, R1, Xc1) X_l2 = np.linspace(Xc2 - R2, Xc2 + R2, 100000) Y2 = Mrc(X_l2, R2, Xc2) X_l3 = np.linspace(Xc3 - R3, Xc3 + R3, 100000) Y3 = Mrc(X_l3, R3, Xc3) X_l4 = np.linspace(Xc4 - R4, Xc4 + R4, 100000) Y4 = Mrc(X_l4, R4, Xc4) X_l5 = np.linspace(Xc5 - R5, Xc5 + R5, 100000) Y5 = Mrc(X_l5, R5, Xc5) X_l8 = np.linspace(Xc8 - R8, Xc8 + R8, 100000) Y8 = Mrc(X_l8, R8, Xc8) X_l6 = np.linspace(Xc6 - R6, Xc6 + R6, 100000) Y6 = Mrc(X_l6, R6, Xc6) X_l9 = np.linspace(Xc9 - R9, Xc9 + R9, 100000) Y9 = Mrc(X_l9, R9, Xc9) X_l7 = np.linspace(Xc7 - R7, Xc7 + R7, 100000) Y7 = Mrc(X_l7, R7, Xc7) # конец кругов X_l9 = np.linspace(Xc9 - R9, Xc9 + R9, 100000) Y9 = Mrc(X_l9, R9, Xc9)

Источник

Читайте также:  Меняем размер шрифта при помощи CSS

I am getting a warning

You didn’t take any precautions for when b**2 — (4*a*c) is a negative number.

>>> import numpy as np >>> >>> np.sqrt(4) 2.0 >>> np.sqrt(-4) __main__:1: RuntimeWarning: invalid value encountered in sqrt nan 

Let’s test if you have negative values:

>>> import numpy as np >>> >>> a = 0.75 + (1.25 - 0.75) * np.random.randn(10000) >>> b = 8 + (12 - 8) * np.random.randn(10000) >>> c = -12 + 2 * np.random.randn(10000) >>> >>> z = b ** 2 - (4 * a * c) >>> print len([_ for _ in z if _ < 0]) 71 

Answer by Damir Walls

I don't get the warning when I build numpy from the master branch, using Python 3.5.2:,If the warning is changed to an error, it becomes FloatingPointError: underflow encountered in sqrt:,Despite the warning, all the resulting values are exactly correct, compared to the builtin sqrt:,Having a single zero in the array is sufficient to cause the warning:

import numpy data = numpy.load("vhat.npy") numpy.sqrt(data) # RuntimeWarning: invalid value encountered in sqrt numpy.sqrt(data[:, 0:900]) # no Warning numpy.sqrt(data[:, 100:2000]) # no Warning numpy.sqrt(data[:, ::-1]) # no Warning発 numpy.sqrt(data[. ]) # RuntimeWarning: invalid value encountered in sqrt 

Answer by Arya Martin

I am trying to draw a sphere in cartesian coordinates. However, I get a half sphere as if np.sqrt gives me only positive values. How can I complete the sphere? Any alternative to np.sqrt?,I know how to draw a sphere in polar coordinates or with sin and cosine functions so I am only interested in drawing it by using x, y, z values such as;,Here is the code gives half sphere and the warning;,if you want a sphere, you can make two half spheres and flip one of them upside down. (I don't know how to fill in the gap between them 🙁 )

Читайте также:  Software javasoft java development kit

I know how to draw a sphere in polar coordinates or with sin and cosine functions so I am only interested in drawing it by using x, y, z values such as;

Here is the code gives half sphere and the warning;

import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(1,2,1, projection = '3d') xs=np.linspace(-1,1, 100) ys=np.linspace(-1,1, 100) xs,ys=np.meshgrid(xs,ys) zs= np.sqrt(1-xs*xs-ys*ys) ax.plot_surface(xs, ys, zs, lw = 0, antialiased = True) 

Answer by Jolie Xiong

I am trying to run a quadratic equation in python. However, it keeps on giving me a warning,Just ensure that you do not have conflicting python environments. Either conda or regular python install.,Numpy does not seem to allow fractional powers of negative numbers, even if the power would not result in a complex number. (I actually had this same problem earlier today, unrelatedly). One workaround is to use,As for the editor: if you have idle installed within your python environment (conda), you should be able to run it without a hitch.

I am trying to run a quadratic equation in python. However, it keeps on giving me a warning

RuntimeWarning: invalid value encountered in sqrt 
import numpy as np a = 0.75 + (1.25 - 0.75)*np.random.randn(10000) print(a) b = 8 + (12 - 8)*np.random.randn(10000) print(b) c = -12 + 2*np.random.randn(10000) print(c) x0 = (-b - np.sqrt(b**2 - (4*a*c)))/(2 * a) print(x0) 

Answer by Keaton Cabrera

Numpy.sqrt() function calculates the square root of every element in the given array.,It throws a RuntimeWarning when the input is a negative number and returns nan as a result.,It returns an array of the square root of each element in the input array, even if out is given.,Python Numpy.sqrt() - Square Root

Syntax of numpy.sqrt()

Example Codes: numpy.sqrt()

import numpy as np arr = [1, 9, 25, 49] arr_sqrt = np.sqrt(arr) print(arr_sqrt) 

Example Codes: numpy.sqrt() With out Parameter

import numpy as np arr = [1, 9, 25, 49] out_arr = np.zeros(4) arr_sqrt = np.sqrt(arr, out_arr) print(out_arr) print(arr_sqrt) 

If out doesn’t have the same shape as arr , it raises a ValueError .

import numpy as np arr = [1, 9, 25, 49] out_arr = np.zeros((2, 2)) arr_sqrt = np.sqrt(arr, out_arr) print(out_arr) print(arr_sqrt) 
Traceback (most recent call last): File "C:\Test\test.py", line 6, in arr_sqrt = np.sqrt(arr, out_arr) ValueError: operands could not be broadcast together with shapes (4,) (2,2) 

Example Codes: numpy.sqrt() With Negative Numbers

import numpy as np arr = [-1, -9, -25, -49] arr_sqrt = np.sqrt(arr) print(arr_sqrt) 
Warning (from warnings module): File "..\test.py", line 5 arr_sqrt = np.sqrt(arr) RuntimeWarning: invalid value encountered in sqrt [nan nan nan nan] 

Example Codes: numpy.sqrt() With Complex Numbers

import numpy as np arr = [3+4j, -5+12j, 8-6j, -15-8j] arr_sqrt = np.sqrt(arr) print(arr_sqrt) 

Answer by Journee Vasquez

Some Python packages for Time Series modeling,`statsmodels `__,In the first lecture, we are mainly concerned with how to model and evaluate time series data.,The time series is modeled as a linear combination of past observations.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RuntimeWarning: invalid value encountered in sqrt #36

RuntimeWarning: invalid value encountered in sqrt #36

Comments

I have ran to this error while I was running ( upsnet_resnet50_coco_1gpu.yaml is just a number of gpu change based on 4gpu.yaml

python -u upsnet/upsnet_end2end_train.py --cfg upsnet/experiments/upsnet_resnet50_coco_1gpu.yaml 
  • running env: pytorch 1.0
  • version: 96b7b5172b7b76446f637f4922b7a2054e46703b and this PR change (
222 2019-05-11 23:08:29,257 | callback.py | line 40 : Batch [1560] Speed: 2.28 samples/sec Train-rpn_cls_loss=0.202601, rpn_bbox_loss=0.119188, rcnn_accuracy=0.918098, cls_loss=0.512433, bbox_loss=0.178919, mask_loss=0.637334, fcn_loss=3.486774, fcn_roi_loss=4.059261, panoptic_accuracy=0.267040, panoptic_loss=2.879008, 223 2019-05-11 23:08:38,512 | callback.py | line 40 : Batch [1580] Speed: 2.16 samples/sec Train-rpn_cls_loss=0.204118, rpn_bbox_loss=0.121994, rcnn_accuracy=0.918320, cls_loss=0.511436, bbox_loss=0.178261, mask_loss=0.637755, fcn_loss=3.488841, fcn_roi_loss=4.060041, panoptic_accuracy=0.265982, panoptic_loss=2.881260, 224 2019-05-11 23:08:47,145 | callback.py | line 40 : Batch [1600] Speed: 2.32 samples/sec Train-rpn_cls_loss=0.208637, rpn_bbox_loss=0.125312, rcnn_accuracy=0.918627, cls_loss=0.510648, bbox_loss=0.177416, mask_loss=0.637829, fcn_loss=3.493248, fcn_roi_loss=4.063709, panoptic_accuracy=0.264609, panoptic_loss=2.885051, 225 2019-05-11 23:08:55,470 | callback.py | line 40 : Batch [1620] Speed: 2.40 samples/sec Train-rpn_cls_loss=0.210174, rpn_bbox_loss=0.125260, rcnn_accuracy=0.918797, cls_loss=0.510753, bbox_loss=0.176945, mask_loss=0.637923, fcn_loss=3.496151, fcn_roi_loss=4.067450, panoptic_accuracy=0.264234, panoptic_loss=2.887030, 226 upsnet/../upsnet/operators/modules/fpn_roi_align.py:38: RuntimeWarning: invalid value encountered in sqrt 227 feat_id = np.clip(np.floor(2 + np.log2(np.sqrt(w * h) / 224 + 1e-6)), 0, 3) 228 Traceback (most recent call last): 229 File "upsnet/upsnet_end2end_train.py", line 403, in 230 upsnet_train() 231 File "upsnet/upsnet_end2end_train.py", line 269, in upsnet_train 232 output = train_model(*batch) 233 File "/opt/xxx_workspace/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py", line 493, in __call__ 234 result = self.forward(*input, **kwargs) 235 File "upsnet/../lib/utils/data_parallel.py", line 110, in forward 236 return self.module(*inputs[0], **kwargs[0]) 237 File "/opt/xxx_workspace/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py", line 493, in __call__ 238 result = self.forward(*input, **kwargs) 239 File "upsnet/../upsnet/models/resnet_upsnet.py", line 139, in forward 240 cls_label, bbox_target, bbox_inside_weight, bbox_outside_weight, mask_target) 241 File "/opt/xxx_workspace/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py", line 493, in __call__ 242 result = self.forward(*input, **kwargs) 243 File "upsnet/../upsnet/models/rcnn.py", line 190, in forward 244 cls_loss = self.cls_loss(cls_score, cls_label) 245 File "/opt/xxx_workspace/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py", line 493, in __call__ 246 result = self.forward(*input, **kwargs) 247 File "/opt/xxx_workspace/anaconda3/lib/python3.7/site-packages/torch/nn/modules/loss.py", line 942, in forward 248 ignore_index=self.ignore_index, reduction=self.reduction) 249 File "/opt/xxx_workspace/anaconda3/lib/python3.7/site-packages/torch/nn/functional.py", line 2056, in cross_entropy 250 return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction) 251 File "/opt/xxx_workspace/anaconda3/lib/python3.7/site-packages/torch/nn/functional.py", line 1869, in nll_loss 252 .format(input.size(0), target.size(0))) 253 ValueError: Expected input batch_size (510) to match target batch_size (512). 

The text was updated successfully, but these errors were encountered:

Источник

Оцените статью