S
S
Sergey Pavlov2014-01-21 23:37:22
Python
Sergey Pavlov, 2014-01-21 23:37:22

How to work with trigonometric functions obtained from a string in matplotlib?

The code is a fragment of a mathematical solver, written just for lulz. Works if the line contains a function that does not affect trigonometry, logarithms, exponents, etc. But when trying to graph the function f(x)=sin(x), for example, an error is thrown: TypeError: only length-1 arrays can be converted to Python scalars. Has anyone experienced this?

import numpy as np
import matplotlib.pyplot as plt
from Tkinter import *
from math import sin
window=Tk()
window.geometry('400x300')
function=Entry(window)
function.pack()
def plot(event):
    a=str(function.get())
    x=np.arange(0,10,0.1)
    y=eval(a)
    plt.plot(x,y)
    plt.show()
but=Button(window)
but.pack()
but.bind('<Button-1>',plot)
window.mainloop()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tsarevfs, 2014-01-22
@Pavlov_dog

When a sine is applied to the input, the following happens:

x = np.arange(0,10,0.1)
y = sin(x)

sin from the math module does not expect to be given a vector, which is reported by this error.
numpy has its own implementation of sin, cos, ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question