【问题标题】:Write math formula in python用python写数学公式
【发布时间】:2017-03-24 02:00:25
【问题描述】:

This is the value I want to calculate. 我写如下,这里我是虚数。我正在使用python和networkx。有人可以帮忙。

import math
import matplotlib
matplotlib.use('TkAgg')
from pylab import *
import cmath
import networkx as nx
import random as rd
import numpy as np

g=nx.karate_club_graph()
for i in g.nodes_iter():
    g.node[i]['theta']=1

a=abs((cmath.exp( (g.node[i]['theta']*(1j)) for i in    g.nodes_iter()))/g.number_of_nodes())

我得到的错误输出是:

"""文件 "",第 1 行,在 runfile('C:/Users/Bhawesh/Desktop/workingdirectory/bookpractice.py', wdir='C:/Users/Bhawesh/Desktop/workingdirectory')

文件“C:\Users\Bhawesh\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py”,第 866 行,在运行文件中 execfile(文件名,命名空间)

文件“C:\Users\Bhawesh\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py”,第 87 行,在 execfile 中 exec(compile(scripttext, filename, 'exec'), glob, loc)

文件“C:/Users/Bhawesh/Desktop/workingdirectory/bookpractice.py”,第 18 行,在 b=abs((cmath.exp( (g.node[i]['theta']*(1j)) for i in g.nodes_iter()))/g.number_of_nodes())

TypeError: 需要一个浮点数 """

【问题讨论】:

  • 有什么问题?
  • 下次,将代码缩进 4 个空格以正确格式化。

标签: python-2.7 networkx


【解决方案1】:

Python 的sqrt 操作不支持负整数。但是,numpy 可以处理复数。虚数 $i$ 在 Python 中由 1j 给出。因此,您必须将方程式转换为:

a=abs((np.exp( (g.node[i]['theta']*(1j)) for i in g.nodes_iter()))/g.number_of_nodes())

【讨论】:

  • 您也可以使用标准库的cmath 模块来获得一个处理复数的exp 函数(不需要像numpy 这样的外部库)。
  • 总是得到以下错误:“TypeError: a float is required”
  • 它可能会提供比错误消息更多的信息。这些信息实际上与找出问题所在有关。请编辑您的问题并包含完整的回溯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-16
  • 1970-01-01
  • 2022-07-04
相关资源
最近更新 更多