Benjamin
Benjamin

Reputation: 145

How to fix the TypeError Corresponding to the Conversion between Types in Python3?

I am running the following code. Since I am new to python, I am trying to understand why I am getting TypeError and how to fix it. Your help is greatly appreciated.

import matplotlib
matplotlib.use('SVG')

import matplotlib.pyplot as pyplot
import random
from numpy import array as ar
import math


N = 1000
data = [random.random() for i in range(N)]
x = ar(data)

a = 1.000000
y = (-1.000000) * a * math.log(x)

'''
pyplot.axis([0, 1, 0, 1])
'''

pyplot.xticks([0.1*k for k in range(0,1)])

'''
pyplot.yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0])
'''

pyplot.title('ElegantPDF')
pyplot.xlabel('x')
pyplot.ylabel('PDF(x)')

xminus = [0] * N 
xplus = [0] * N
yminus = [0] * N
yplus = [0] * N


pyplot.plot(x,y, color='blue', linestyle='', marker='o', label='Probability Distribuiton Function')
pyplot.errorbar(x, y, xerr=(xminus, xplus), yerr=(yminus, yplus), ecolor='green', elinewidth=2.0, capsize=20.0)
pyplot.legend(title='The legend')
pyplot.savefig('Elegant.svg')

Traceback (most recent call last): File "ElegantPDF.py", line 15, in y = (-1.000000) * a * math.log(x) TypeError: only length-1 arrays can be converted to Python scalars

Upvotes: 0

Views: 136

Answers (2)

Zahra
Zahra

Reputation: 7197

math.log function expects a scalar as its input parameter while x is an array.

the following line should fix the issue:

y = [ math.log(x[i]) for i in range(0,len(x)) ]

it is equivalent to y = np.log(x)

Upvotes: 1

Reti43
Reti43

Reputation: 9796

Your error occurs because math.log() expects a scalar, or scalar-like arrays.

import math
import numpy as np

math.log(np.array([3, 4])) # will fail
math.log(np.array([3]))    # same as math.log(3)

If you want to calculate the log of all elements, use np.log() instead.

np.log(np.array([3, 4]))   # will get array([ 1.09861229,  1.38629436])

Upvotes: 2

Related Questions