0

I am very new to programming, I am trying to code a function that prints the variance and mean based on a alpha I type in, or if I am not typing anything it defaults to 1.96. When I don't type anything it works fine, but when I type for example 1.625, it returns "TypeError: can't multiply sequence by non-int of type 'numpy.float64'"

Here is my code:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy import stats

def estimat(data):
    var = np.var(data, ddof = 1)
    forv = np.mean(data)
    z = a*np.sqrt(var/len(data))
    konf = {forv+z,forv-z}
    return {"varians": var, "forventning,":forv, "konfidensintervall":konf}

x = stats.norm.rvs(0,1,100)

a = input("Enter your alpha:  ") or 1.96
print (estimat(x))
Omniswitcher
  • 368
  • 3
  • 13
hihixd
  • 1
  • 3

1 Answers1

0

You were almost there but had to change how your alpha is entered a little bit:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy import stats

def estimat(data):
    var = np.var(data, ddof = 1)
    forv = np.mean(data)
    z = float(a)*np.sqrt(var/len(data))
    konf = {forv+z,forv-z}
    return {"varians": var, "forventning,":forv, "konfidensintervall":konf}

x = stats.norm.rvs(0,1,100)

print("Enter your alpha:  ")
a = input()
if(a == ''):
    a = 1.96

print (estimat(x))
# print (a)

The text should not be inside an input() so I placed above it with a print().

The # print(a) was there to check if the right entered/automated number was taken, I left it in the code so you can always check what happens if you alter your code.

edit @Ignatius Reilly comment under the uestion is cleaner and more efficient

Omniswitcher
  • 368
  • 3
  • 13
  • My suggestion in comments is cleaner for reading numbers, but it will raise an error if the input is empty. Your solution can deal with both numbers and empty input. – Ignatius Reilly Aug 26 '22 at 15:26