(Matlab Coder)Domain error. To compute complex results from real x, use 'acosd(complex(x))'

조회 수: 6 (최근 30일)
When I try to evaluate an acosd value, the generated mex execution is not consistent with the original function and often errors out?
function out = triFun(in)%#codegen
out = real(acosd(in));
end
I use the following statement to generate successfully:
codegen -config:mex triFun.m -args {0.5}
Then test it with the following statement:
for i = 1:10
a = rand(1,2);
b = a;
distA = sqrt(a(1).^2+a(2).^2);
distB = sqrt(b(1).^2+b(2).^2);
val = dot(a,b)./(distA.*distB);
out1 = triFun(val) % always OK
out2 = triFun_mex(val) % sometimes failed, Domain error. To compute complex results from real x, use 'acosd(complex(x))' ???
end
output error:
test_codegen_mex
out1 =
0
Domain error. To compute complex results from real x, use 'acosd(complex(x))'.
Error in acosd (line 13)
coder.internal.error('Coder:toolbox:ElFunDomainError',mfilename);
Error in triFun (line 2)
out = real(acosd(in));
Error in test_codegen_mex (line 12)
out2 = triFun_mex(val) % sometimes failed, Domain error. To compute complex results from real x, use 'acosd(complex(x))' ???
Question:
Obviously, the a,b I gave are equal and the val value should be equal to 1. There will be no complexity, but out2 will mistake the result for a complex number and out1 will not. How can I modify this to achieve the goal of consistent results?
Run In Matlab R2023a

채택된 답변

Bruno Luong
Bruno Luong 2023년 9월 28일
편집: Bruno Luong 2023년 9월 28일
"Obviously, the a,b I gave are equal and the val value should be equal to 1"
wrong. Before claming anything, you should first check.
format long
while true
a = rand(1,2);
b = a;
distA = sqrt(a(1).^2+a(2).^2);
distB = sqrt(b(1).^2+b(2).^2);
val = dot(a,b)./(distA.*distB);
if abs(val) > 1
a
b
val
exceedvalto1 = val-1
fprintf('val can not be == 1 with numerical error\n')
break
end
end
a = 1×2
0.894442198246962 0.268453115545912
b = 1×2
0.894442198246962 0.268453115545912
val =
1.000000000000000
exceedvalto1 =
2.220446049250313e-16
val can not be == 1 with numerical error
Fix: you need to truncate val by safety
val = max(min(val,1),-1);
before calling acosd

추가 답변 (0개)

태그

제품


릴리스

R2023b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by