本文介绍了Numpy, RuntimeWarning: sqrt 中遇到无效值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在笛卡尔坐标系中绘制一个球体.但是,我得到一个半球体,好像 np.sqrt 只给我正值.我怎样才能完成球体?任何 np.sqrt 的替代品?

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?

我知道如何在极坐标或正弦和余弦函数中绘制球体,所以我只对使用 x、y、z 值绘制它感兴趣,例如;

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;

x**2+y**2+z**2=1

这是给出半球和警告的代码;

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)

推荐答案

根据定义,平方根函数给出平方根数的正(也称为原则)根.

the square root function, by definition, gives the positive (also called principle) root of the number it's square rooting.

负平方根"是方程 a^n = b 的一组更一般解的一部分,其中 n 是根的次数,b 是您要取其平方根的数字,并且a 是解决方案(a 和 b 可能很复杂).

the "negative square root" is part of a more general set of solutions to the equation a^n = b, where n is the degree of the root, b is the number you're taking the square root of, and a is the solution (a and b might be complex).

关键是一般平方根"是不明确的,因为它对一个输入有一堆解决方案.它不是(数学)函数.numpy用的是大家都用的标准,就是正/原理解.

the point is that the "general square root" is ambiguous because it has a bunch of solutions for one input. it's not a (mathematical) function. numpy uses the standard that everyone uses, which is the positive/principle solution.

如果你想要一个球体,你可以制作两个半球体并将其中一个倒置.(我不知道如何填补他们之间的空白:()

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 :( )

就运行时警告而言,您在网格的角落处取负数的平方根,在那里没有(真正的)圆的解决方案.那里应该没有解决方案,因为那里不存在圆圈.(如果你打印 zs,你应该看到 NaN.)

as far as the runtime warning, you're taking the square root OF a negative number at the corners of the grid, where there's no (real) solution to the circle. there should be no solution there, since the circle doesn't exist there. (if you print zs, you should see NaNs.)

这篇关于Numpy, RuntimeWarning: sqrt 中遇到无效值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 15:30