taichi-dev / taichi

Productive, portable, and performant GPU programming in Python.
https://taichi-lang.org
Apache License 2.0
25.5k stars 2.28k forks source link

The output is 0.0 when printing a float less than 0.0000005 in kernel #4188

Open ayanlv opened 2 years ago

ayanlv commented 2 years ago

The second print is more logical

import taichi as ti
ti.init(arch=ti.gpu)

x = ti.field(ti.f32, shape=())

@ti.kernel
def main():
    x[None] = 0.00000012345678
    print(x[None])   # 0.000000

main()
print(x[None])       # 1.234567861274627e-07
strongoier commented 2 years ago

In this case, C printf is called and %f is used as the format string for ti.f32. According to https://en.cppreference.com/w/cpp/io/c/fprintf, for %f,

the default precision is 6.

Should we change the behavior to align it with Python better? @lin-hitonami @ailzhang @k-ye Personally, I prefer to document it rather than change it.

k-ye commented 2 years ago

Hmm, I actually feel it's better to align with Python. However, we should leverage Python's infrastructure to help us get there. I.e. instead of composing the string in C++, we just pass back the raw data, and let Python do the string formatting + printing

ailzhang commented 2 years ago

@k-ye In this case if we are talking about the format string in PrintStmt we won't be able to pass it back to python in the middle of the execution right? @strongoier I'm thinking that maybe we can switch to using scientific notation by default?

int main()
{
  float f = 0.0000001;
  std::printf("%E" , f);  // 1.000000E-07 
}