Bird
0
0

You have two arrays:

hard📝 Application Q15 of 15
NumPy - Array Operations
You have two arrays:
arr_int = np.array([1000, 2000], dtype=np.int16)
arr_float = np.array([0.1, 0.2], dtype=np.float32)

You want to add them and keep the result as float32 to save memory. Which code correctly achieves this with type promotion?
Aresult = arr_int.astype(np.float32) + arr_float
Bresult = arr_int + arr_float.astype(np.float64)
Cresult = arr_int + arr_float
Dresult = arr_int.astype(np.int32) + arr_float
Step-by-Step Solution
Solution:
  1. Step 1: Understand default type promotion

    Adding int16 and float32 promotes to float64 by default, increasing memory.
  2. Step 2: Convert int16 to float32 before addition

    By converting arr_int to float32, adding float32 arrays keeps result as float32, saving memory.
  3. Step 3: Check other options

    result = arr_int + arr_float.astype(np.float64) promotes to float64, increasing memory. result = arr_int + arr_float promotes to float64 by default. result = arr_int.astype(np.int32) + arr_float promotes int16 to int32, then adds float32, promoting to float64.
  4. Final Answer:

    result = arr_int.astype(np.float32) + arr_float -> Option A
  5. Quick Check:

    Cast int to float32 first to keep float32 result [OK]
Quick Trick: Cast int to float32 before adding float32 to keep dtype [OK]
Common Mistakes:
  • Ignoring default promotion to float64
  • Casting float to float64 increasing memory
  • Not casting int before addition

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes