-1

I'm new with python. I learn it myself and figure out what happen but now, I'm really stuck. Please help me to figure out my problem.

import matplotlib.pyplot as plt
import math

x = [-0.006,-0.005,-0.004,-0.003,-0.002,-0.001,0,0.001,0.002,0.003,0.004,0.005,0.00]
y = [220*(1 - (0.85*math.exp(-math.pi**2/math.log(2)*(x*0.53*10**-9/759.5*10**-9)**2)))]

plt.plot(x,y)
plt.xlabel('optical path difference')
plt.ylabel('coincidence counts in 3 min')

plt.show()

After run it, it returns an error:

TypeError: can't multiply sequence by non-int of type 'float'

How do I need to change my code such that I can multiply the list x with a float?

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • 1
    For the record, there are a bazillion variations on this problem you could have checked, most of them with the exact error message in the title. Please look at the suggested related questions first next time. – ShadowRanger May 24 '17 at 01:18

2 Answers2

0

x is a Python list. x*0.53 is non-sensical (sequence multiplication for anything but numpy types means "repeat sequence that many times", and it's a discrete multiplier, you can't take the first 53% of the sequence).

Did you mean to convert x to a numpy array or something? Or process each element individually?

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • the x is a value from -0.006 until 0.006, I want to substitute it into the y formula automatically when it run. – munirah May 24 '17 at 01:32
0

You cannot multiply a list with a float value. While lists can be "multiplied" with an integer, this would not help you here.

Instead you may use numpy. A numpy array can be multiplied by a single number or another numpy array.

[1,2,3] * 3                           # [1, 2, 3, 1, 2, 3, 1, 2, 3]
[1,2,3] * 3.3                         # can't multiply sequence by non-int of type 'float'
np.array([1,2,3]) * 3                 # [3 6 9]
np.array([1,2,3]) * np.array([1,2,3]) # [1 4 9]

So the solution here is to use make x a numpy array first. You then also have to remove the square brackets in y.

import matplotlib.pyplot as plt
import numpy as np

x = [-0.006,-0.005,-0.004,-0.003,-0.002,-0.001,0,0.001,0.002,0.003,0.004,0.005,0.006]
x = np.array(x)
y = 220*(1 - (0.85*np.exp(-np.pi**2/np.log(2)*(x*0.53e-9/759.5e-9)**2)))

plt.plot(x,y)
plt.xlabel('optical path difference')
plt.ylabel('coincidence counts in 3 min')

plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712