The problem about argument of hist on python

  0 import numpy as np
  1 import ROOT
  2 list1=[0,10,30]
  3 print(np.array(list1))
  4 h1=ROOT.TH1F("h1","",2,np.array(list1))
  5 h1.SetBinContent(1,1)
  6 h1.SetBinContent(2,3)
  7 h1.Draw()

Dear experts,I think there is no problem, the number of arguments is right,but I got the following error.My friend told me if I wrote as following code,I will succeed.I want to know the reason.Thank you!

  4 h1=ROOT.TH1F("h1","",2,np.array(list1,np.float32))

_ROOT Version:6.26/06
Platform: Mac
Compiler: Not Provided
__

Hi @xiangjun!

The problem is that by default, an np.array() is of type int64 if you have integers in your list, or float64 if you use floating point numbers.

You create your list1 with integers, but then you use this integer array to fill a TH1F, which stores floats (float32 in numpy). However, you can only pass numpy arrays to functions that accept a C-style array if the type matches exactly. Otherwise you get the error that you saw.

The way to work around this is to either construct the numpy array with the correct type as your friend suggests, or use doubles everywhere (which means using the TH1D class):

import numpy as np
import ROOT
list1 = [0., 10., 30.]
print(np.array(list1))
h1=ROOT.TH1D("h1","",2,np.array(list1))
h1.SetBinContent(1,1)
h1.SetBinContent(2,3)
h1.Draw()

I hope this clears things up!
Jonas

Thank you!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.