본문 바로가기
프로그래밍 언어/Mathematica

[Mathematica] Convert E-notation (C-language, Fortran) to numbers in Mathematica

by Physics 2023. 11. 19.
728x90

 

이럴 때, 이런 텍스트 파일을 Import로 불러올 경우, string으로 인식을 하고 숫자로 인식을 하지 못한다. 따라서, E를 10으로 메스메티카에서 인식을 시키기 위해선 아래와 같은 방법들을 사용할 수 있다. 

 

ToExpression@StringReplace[]  
ImportString[] 
Interpreter["Number"] 
Internal`StringToReal 

 

1. ToExpression 사용 

>>> convert[input_?StringQ]:=ToExpression@StringReplace[input, "e"->"*10^"];
>>> ToExpression@StringReplace["1.00e-10, "e"->"*10^"]

1) 일반적으로 ToExpression은 데이터를 읽어 변환할 때 사용하는 것을 추천하지는 않는다. 

 

2. ImportString 사용

>>> ImportString["10.0e-10", "JSON"]

 

3. Interpreter["Number"]

>>> Interpreter["Number"]["1.00e-5"]

1) Mathematica Version 10에서부터 생긴 함수로 특정 객체를 사용자가 지정한 형태로 변환하는 함수 
2) 속도 측면에서는 다른 코드와 비교했을 때, 압도적으로 느림 

 

4. Internal`StringToReal

>>> Needs["GeneralUtilities`"];
>>> Internal`StringToMReal["1.23e-5"];

1) Internal`StringToDouble[]은 Mathematica Version 12.3 이후에는 찾을 수 없으며, 위 함수로 변경이 되었.    
2) 해당 함수를 사용하기 위해선, "GeneralUtilities" 패키지를 불러와야 한다. 
3) Internal`StringToMReal은 Undocumented built-in function 중 하나로 잘못된 결과값을 줄 수 있는 경우가 있다. 

 

5. 속도 비교

string = "1.00e-10";
ToExpression@StringReplace[string, "e" -> "*10^"] // AbsoluteTiming
ImportString[string, "JSON"] // AbsoluteTiming
Interpreter["Number"][string] // AbsoluteTiming
Internal`StringToMReal[string] // AbsoluteTiming 
>>> {0.0000377, 1.*10^-10}
>>> {0.0040972, 1.*10^-10}
>>> {0.014389, 1.*10^-10}
>>> {0.0000273, 1.*10^-10}

따라서 속도 측면에서 가장 빠른 것은 Internal`StringToMReal임을 알 수 있다. 

 

Reference 

[1] https://mathematica.stackexchange.com/questions/49289/converting-strings-of-the-form-1-34e5-to-real-numbers   
[2] https://mathematica.stackexchange.com/questions/1737/how-do-you-convert-a-string-containing-a-number-in-c-scientific-notation-to-a-ma

728x90

댓글