Home > Enterprise >  Line of best fit
Line of best fit

Time:05-21

Can someone help me in this code, im having a problem in my input saying it could not convert string to float.

import statistics 
import numpy as np

print("When entering some values it should be like this (1,2,3,4,5)")
xs=np.array(input("Enter some values of x coordinate: "), dtype=np.float64)
ys=np.array(input("Enter some values of y coordinate: "), dtype=np.float64)
  
    
def line_slope_intercept(xs,ys):
    
    m=(((statistics.mean(xs)*statistics.mean(ys))- statistics.mean(xs*ys))/
       ((statistics.mean(xs)*statistics.mean(xs))-statistics.mean(xs*xs)) )
    b=statistics.mean(ys)-m*statistics.mean(xs)
    return m, b
m,b=line_slope_intercept(xs,ys)

print(format(m,".2f"))
print(format(b,".2f"))

print("y=",format(m,".2f"),"x"," ",format(b,".2f") )

CodePudding user response:

The input cannot accept a list of values. By default, it is a string so you have to convert it to float. If you input (1,2,3,4,5) to it, surely it cannot convert that string into an array.

I propose another solution:

print("When entering some values it should be like this (1,2,3,4,5)")
xs = input("Enter some values of x coordinate: ")
ys = input("Enter some values of y coordinate: ")
xs=np.array([float(x) for x in xs[1:-1].split(',')], dtype=np.float64)
ys=np.array([float(x) for x in ys[1:-1].split(',')], dtype=np.float64)

When you input (1,2,3,4,5) as a string, [1:-1] will take all characters from the first index to before the last index, so it will return the string 1,2,3,4,5. Then we use split(',') to split the string into elements that are separated by , in the string, convert it to float and use it as usual.

CodePudding user response:

The actual error you're getting is this:

Traceback (most recent call last):
  File "C:/Users/isaac/OneDrive/Documents/justfortesting.py", line 15, in <module>
    m,b=line_slope_intercept(xs,ys)
  File "C:/Users/isaac/OneDrive/Documents/justfortesting.py", line 11, in line_slope_intercept
    m=(((statistics.mean(xs)*statistics.mean(ys))- statistics.mean(xs*ys))/
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\statistics.py", line 324, in mean
    if iter(data) is data:
TypeError: iteration over a 0-d array

I'm not familiar with the statistics module, but this is the answer I found somewhere else:

TypeError: iteration over a 0-d array solution

  • Related