修正逆幂函数实现错误:cw_2_ZMA的逆函数ZMA_2_cw结果不符
Looking at your code, there are two key mistakes preventing the inverse function from working correctly:
1. Incorrect PCW Calculation
The original function uses ZMA = C * PCW^(-0.88) where C = -(1000 * np.log(0.05))/144.7. To solve for PCW, you need to rearrange this equation properly:
- Start with
ZMA = C / PCW^(0.88) - Rearrange to
PCW^(0.88) = C / ZMA - Raise both sides to the power of
1/0.88:PCW = (C / ZMA)^(1/0.88)
Your current code uses (1/C) * ZMA^(-1/0.88), which is not equivalent to the correct expression. This is because (C/ZMA)^(1/0.88) = C^(1/0.88) * ZMA^(-1/0.88), not (1/C) * ZMA^(-1/0.88).
2. Wrong Conversion from PCW to cw
In the original function, PCW = cw + bs, so solving for cw gives cw = PCW - bs. Your code incorrectly multiplies PCW by 1000 before subtracting bs—this extra multiplication is unnecessary and introduces a huge error.
Corrected Code
Here's the fixed version of ZMA_2_cw:
import numpy as np #define input arrays and variables cw_array=np.arange(0,10,1) bs = 1.592278e-4 #functions def cw_2_ZMA(cw): PCW = np.add(cw, bs) ZMA = -(1000 * np.log(0.05) / 144.7)* np.power(PCW, -0.88) return ZMA def ZMA_2_cw(ZMA): # Calculate the constant C from the original function C = -(1000 * np.log(0.05)) / 144.7 # Correct PCW calculation PCW = np.power(C / ZMA, 1 / 0.88) # Correct conversion to cw cw = PCW - bs return cw #execute functions ZMA_calc=cw_2_ZMA(cw_array) cw_calc=ZMA_2_cw(ZMA_calc) #print arrays print("cw_array=", cw_array[:]) print("cw_calc=", np.round(cw_calc[:],1))
Expected Output
When you run this corrected code, the output will be:
('cw_array=', array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])) ('cw_calc=', array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]))
Now the inverse function accurately recovers the original cw_array values!
内容的提问来源于stack exchange,提问作者PythonForeCats

